Merging with mozilla-central. Manually merged: content/canvas/src/nsCanvasRenderingContext2D.cpp ipc/ipdl/Makefile.in toolkit/toolkit-tiers.mk toolkit/xre/nsEmbedFunctions.cpp
authorDoug Turner <dougt@dougt.org>
Mon, 28 Jun 2010 16:33:19 -0700
changeset 46924 18f64f620273539874c4a5b0d9148efc29b320e6
parent 46923 8e4ceb3b4da549b8c404d2fbae12e89ab6bdd041 (current diff)
parent 46383 da62b72e9ff11fe73501b8e89fc19165d1e28036 (diff)
child 46925 4b99f09316ada2cb4f7185a5ef2aad84f1bac669
push id14210
push userdougt@mozilla.com
push dateThu, 01 Jul 2010 06:28:42 +0000
treeherdermozilla-central@3aff97777291 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone1.9.3a6pre
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merging with mozilla-central. Manually merged: content/canvas/src/nsCanvasRenderingContext2D.cpp ipc/ipdl/Makefile.in toolkit/toolkit-tiers.mk toolkit/xre/nsEmbedFunctions.cpp
build/automation.py.in
caps/src/nsScriptSecurityManager.cpp
chrome/src/nsChromeRegistry.cpp
configure.in
content/base/src/nsContentUtils.cpp
content/base/src/nsDocument.cpp
content/base/src/nsFrameLoader.cpp
content/base/src/nsGkAtomList.h
content/base/src/nsObjectLoadingContent.cpp
content/canvas/src/Makefile.in
content/canvas/src/nsCanvasRenderingContext2D.cpp
content/events/src/nsDOMEvent.cpp
content/events/src/nsDOMEvent.h
content/html/content/src/nsGenericHTMLElement.cpp
content/html/document/src/nsHTMLDocument.cpp
content/html/document/test/test_bug386495.html
content/xul/content/src/nsXULElement.cpp
docshell/base/nsDocShell.cpp
dom/Makefile.in
dom/base/nsDOMClassInfo.cpp
dom/base/nsDOMClassInfoClasses.h
dom/base/nsGlobalWindow.cpp
dom/base/nsGlobalWindow.h
dom/indexedDB/IDBCursorRequest.cpp
dom/indexedDB/IDBCursorRequest.h
dom/indexedDB/IDBDatabaseRequest.cpp
dom/indexedDB/IDBDatabaseRequest.h
dom/indexedDB/IDBIndexRequest.cpp
dom/indexedDB/IDBIndexRequest.h
dom/indexedDB/IDBObjectStoreRequest.cpp
dom/indexedDB/IDBObjectStoreRequest.h
dom/indexedDB/IDBTransactionRequest.cpp
dom/indexedDB/IDBTransactionRequest.h
dom/indexedDB/IndexedDatabaseRequest.cpp
dom/indexedDB/IndexedDatabaseRequest.h
dom/indexedDB/nsIIDBCursorRequest.idl
dom/indexedDB/nsIIDBDatabaseRequest.idl
dom/indexedDB/nsIIDBIndexRequest.idl
dom/indexedDB/nsIIDBObjectStoreRequest.idl
dom/indexedDB/nsIIDBTransactionRequest.idl
dom/indexedDB/nsIIndexedDatabaseRequest.idl
dom/src/geolocation/Makefile.in
gfx/idl/Makefile.in
gfx/idl/geniid.pl
gfx/idl/gfxIFormats.idl
gfx/idl/gfxidltypes.idl
gfx/idl/nsIFontEnumerator.idl
gfx/idl/nsIScriptableRegion.idl
gfx/public/Makefile.in
gfx/public/X11Util.h
gfx/public/gfxCore.h
gfx/public/nsColor.h
gfx/public/nsColorNameList.h
gfx/public/nsColorNames.h
gfx/public/nsCoord.h
gfx/public/nsFont.h
gfx/public/nsGfxCIID.h
gfx/public/nsIDeviceContext.h
gfx/public/nsIFontMetrics.h
gfx/public/nsIRegion.h
gfx/public/nsIRenderingContext.h
gfx/public/nsITheme.h
gfx/public/nsMargin.h
gfx/public/nsPoint.h
gfx/public/nsRect.h
gfx/public/nsRegion.h
gfx/public/nsSize.h
gfx/public/nsThemeConstants.h
gfx/public/nsTransform2D.h
gfx/src/psshared/Makefile.in
gfx/src/psshared/nsCUPSShim.cpp
gfx/src/psshared/nsCUPSShim.h
gfx/src/psshared/nsPSPrinters.cpp
gfx/src/psshared/nsPSPrinters.h
gfx/src/psshared/nsPaperPS.cpp
gfx/src/psshared/nsPaperPS.h
gfx/src/psshared/psSharedCore.h
gfx/thebes/gfxSharedImageSurface.cpp
gfx/thebes/gfxSharedImageSurface.h
gfx/thebes/public/GLContext.h
gfx/thebes/public/GLContextProvider.h
gfx/thebes/public/GLDefs.h
gfx/thebes/public/GLXLibrary.h
gfx/thebes/public/Makefile.in
gfx/thebes/public/WGLLibrary.h
gfx/thebes/public/gfx3DMatrix.h
gfx/thebes/public/gfxASurface.h
gfx/thebes/public/gfxAlphaRecovery.h
gfx/thebes/public/gfxAndroidPlatform.h
gfx/thebes/public/gfxBeOSPlatform.h
gfx/thebes/public/gfxBeOSSurface.h
gfx/thebes/public/gfxColor.h
gfx/thebes/public/gfxContext.h
gfx/thebes/public/gfxD2DSurface.h
gfx/thebes/public/gfxDDrawSurface.h
gfx/thebes/public/gfxDWriteFonts.h
gfx/thebes/public/gfxDirectFBSurface.h
gfx/thebes/public/gfxFT2FontBase.h
gfx/thebes/public/gfxFT2Fonts.h
gfx/thebes/public/gfxFont.h
gfx/thebes/public/gfxFontConstants.h
gfx/thebes/public/gfxFontTest.h
gfx/thebes/public/gfxFontUtils.h
gfx/thebes/public/gfxGdkNativeRenderer.h
gfx/thebes/public/gfxGlitzSurface.h
gfx/thebes/public/gfxImageSurface.h
gfx/thebes/public/gfxMatrix.h
gfx/thebes/public/gfxOS2Fonts.h
gfx/thebes/public/gfxOS2Platform.h
gfx/thebes/public/gfxOS2Surface.h
gfx/thebes/public/gfxPDFSurface.h
gfx/thebes/public/gfxPSSurface.h
gfx/thebes/public/gfxPangoFonts.h
gfx/thebes/public/gfxPath.h
gfx/thebes/public/gfxPattern.h
gfx/thebes/public/gfxPlatform.h
gfx/thebes/public/gfxPlatformGtk.h
gfx/thebes/public/gfxPlatformMac.h
gfx/thebes/public/gfxPoint.h
gfx/thebes/public/gfxQPainterSurface.h
gfx/thebes/public/gfxQtNativeRenderer.h
gfx/thebes/public/gfxQtPlatform.h
gfx/thebes/public/gfxQuartzImageSurface.h
gfx/thebes/public/gfxQuartzNativeDrawing.h
gfx/thebes/public/gfxQuartzPDFSurface.h
gfx/thebes/public/gfxQuartzSurface.h
gfx/thebes/public/gfxRect.h
gfx/thebes/public/gfxSharedImageSurface.h
gfx/thebes/public/gfxSkipChars.h
gfx/thebes/public/gfxTextRunCache.h
gfx/thebes/public/gfxTextRunWordCache.h
gfx/thebes/public/gfxTypes.h
gfx/thebes/public/gfxUserFontSet.h
gfx/thebes/public/gfxUtils.h
gfx/thebes/public/gfxWindowsNativeDrawing.h
gfx/thebes/public/gfxWindowsPlatform.h
gfx/thebes/public/gfxWindowsSurface.h
gfx/thebes/public/gfxXlibNativeRenderer.h
gfx/thebes/public/gfxXlibSurface.h
gfx/thebes/src/GLContext.cpp
gfx/thebes/src/GLContextProviderCGL.mm
gfx/thebes/src/GLContextProviderEGL.cpp
gfx/thebes/src/GLContextProviderGLX.cpp
gfx/thebes/src/GLContextProviderNull.cpp
gfx/thebes/src/GLContextProviderOSMesa.cpp
gfx/thebes/src/GLContextProviderWGL.cpp
gfx/thebes/src/Makefile.in
gfx/thebes/src/cairo-gdk-utils.c
gfx/thebes/src/cairo-gdk-utils.h
gfx/thebes/src/cairo-xlib-utils.c
gfx/thebes/src/cairo-xlib-utils.h
gfx/thebes/src/genUnicodeScriptData.pl
gfx/thebes/src/gfxASurface.cpp
gfx/thebes/src/gfxAlphaRecovery.cpp
gfx/thebes/src/gfxAndroidPlatform.cpp
gfx/thebes/src/gfxAtomList.h
gfx/thebes/src/gfxAtoms.cpp
gfx/thebes/src/gfxAtoms.h
gfx/thebes/src/gfxBeOSPlatform.cpp
gfx/thebes/src/gfxBeOSSurface.cpp
gfx/thebes/src/gfxContext.cpp
gfx/thebes/src/gfxCoreTextShaper.cpp
gfx/thebes/src/gfxCoreTextShaper.h
gfx/thebes/src/gfxD2DSurface.cpp
gfx/thebes/src/gfxDDrawSurface.cpp
gfx/thebes/src/gfxDWriteCommon.cpp
gfx/thebes/src/gfxDWriteCommon.h
gfx/thebes/src/gfxDWriteFontList.cpp
gfx/thebes/src/gfxDWriteFontList.h
gfx/thebes/src/gfxDWriteFonts.cpp
gfx/thebes/src/gfxDWriteShaper.cpp
gfx/thebes/src/gfxDWriteShaper.h
gfx/thebes/src/gfxDWriteTextAnalysis.cpp
gfx/thebes/src/gfxDWriteTextAnalysis.h
gfx/thebes/src/gfxDirectFBSurface.cpp
gfx/thebes/src/gfxDllDeps.cpp
gfx/thebes/src/gfxFT2FontBase.cpp
gfx/thebes/src/gfxFT2FontList.cpp
gfx/thebes/src/gfxFT2FontList.h
gfx/thebes/src/gfxFT2Fonts.cpp
gfx/thebes/src/gfxFT2Utils.cpp
gfx/thebes/src/gfxFT2Utils.h
gfx/thebes/src/gfxFont.cpp
gfx/thebes/src/gfxFontMissingGlyphs.cpp
gfx/thebes/src/gfxFontMissingGlyphs.h
gfx/thebes/src/gfxFontTest.cpp
gfx/thebes/src/gfxFontUtils.cpp
gfx/thebes/src/gfxFontconfigUtils.cpp
gfx/thebes/src/gfxFontconfigUtils.h
gfx/thebes/src/gfxGDIFont.cpp
gfx/thebes/src/gfxGDIFont.h
gfx/thebes/src/gfxGDIFontList.cpp
gfx/thebes/src/gfxGDIFontList.h
gfx/thebes/src/gfxGDIShaper.cpp
gfx/thebes/src/gfxGDIShaper.h
gfx/thebes/src/gfxGdkNativeRenderer.cpp
gfx/thebes/src/gfxHarfBuzzShaper.cpp
gfx/thebes/src/gfxHarfBuzzShaper.h
gfx/thebes/src/gfxImageSurface.cpp
gfx/thebes/src/gfxMacFont.cpp
gfx/thebes/src/gfxMacFont.h
gfx/thebes/src/gfxMacPlatformFontList.h
gfx/thebes/src/gfxMacPlatformFontList.mm
gfx/thebes/src/gfxMatrix.cpp
gfx/thebes/src/gfxOS2Fonts.cpp
gfx/thebes/src/gfxOS2Platform.cpp
gfx/thebes/src/gfxOS2Surface.cpp
gfx/thebes/src/gfxPDFSurface.cpp
gfx/thebes/src/gfxPSSurface.cpp
gfx/thebes/src/gfxPangoFonts.cpp
gfx/thebes/src/gfxPath.cpp
gfx/thebes/src/gfxPattern.cpp
gfx/thebes/src/gfxPlatform.cpp
gfx/thebes/src/gfxPlatformFontList.cpp
gfx/thebes/src/gfxPlatformFontList.h
gfx/thebes/src/gfxPlatformGtk.cpp
gfx/thebes/src/gfxPlatformMac.cpp
gfx/thebes/src/gfxQPainterSurface.cpp
gfx/thebes/src/gfxQtNativeRenderer.cpp
gfx/thebes/src/gfxQtPlatform.cpp
gfx/thebes/src/gfxQuartzImageSurface.cpp
gfx/thebes/src/gfxQuartzNativeDrawing.cpp
gfx/thebes/src/gfxQuartzPDFSurface.cpp
gfx/thebes/src/gfxQuartzSurface.cpp
gfx/thebes/src/gfxRect.cpp
gfx/thebes/src/gfxScriptItemizer.cpp
gfx/thebes/src/gfxScriptItemizer.h
gfx/thebes/src/gfxSharedImageSurface.cpp
gfx/thebes/src/gfxSkipChars.cpp
gfx/thebes/src/gfxTextRunCache.cpp
gfx/thebes/src/gfxTextRunWordCache.cpp
gfx/thebes/src/gfxUnicodeProperties.cpp
gfx/thebes/src/gfxUnicodeProperties.h
gfx/thebes/src/gfxUnicodePropertyData.cpp
gfx/thebes/src/gfxUniscribeShaper.cpp
gfx/thebes/src/gfxUniscribeShaper.h
gfx/thebes/src/gfxUserFontSet.cpp
gfx/thebes/src/gfxUtils.cpp
gfx/thebes/src/gfxWindowsNativeDrawing.cpp
gfx/thebes/src/gfxWindowsPlatform.cpp
gfx/thebes/src/gfxWindowsSurface.cpp
gfx/thebes/src/gfxXlibNativeRenderer.cpp
gfx/thebes/src/gfxXlibSurface.cpp
gfx/thebes/src/ignorable.x-ccmap
gfx/thebes/src/nsUnicodeRange.cpp
gfx/thebes/src/nsUnicodeRange.h
gfx/thebes/src/woff-private.h
gfx/thebes/src/woff.c
gfx/thebes/src/woff.h
ipc/ipdl/Makefile.in
layout/base/nsPresContext.cpp
layout/build/Makefile.in
layout/build/nsLayoutModule.cpp
layout/generic/nsFrameFrame.cpp
modules/libpref/src/init/all.js
modules/plugin/base/src/nsPluginHost.cpp
netwerk/cookie/nsCookieService.cpp
toolkit/components/console/content/headsUpDisplay.css
toolkit/library/libxul-config.mk
toolkit/toolkit-makefiles.sh
toolkit/toolkit-tiers.mk
toolkit/xre/nsAppRunner.cpp
toolkit/xre/nsEmbedFunctions.cpp
widget/public/nsIAccelerometer.idl
widget/src/android/nsAccelerometerAndroid.cpp
widget/src/android/nsAccelerometerAndroid.h
widget/src/android/nsWindow.cpp
widget/src/cocoa/nsAccelerometerX.h
widget/src/cocoa/nsAccelerometerX.mm
widget/src/gtk2/nsAccelerometerUnix.cpp
widget/src/gtk2/nsAccelerometerUnix.h
widget/src/windows/nsAccelerometerWin.cpp
widget/src/windows/nsAccelerometerWin.h
widget/src/windows/nsWindow.cpp
widget/src/windows/nsWindow.h
widget/src/xpwidgets/nsAccelerometer.cpp
widget/src/xpwidgets/nsAccelerometer.h
xpcom/build/nsXULAppAPI.h
--- a/accessible/public/nsIAccessibilityService.h
+++ b/accessible/public/nsIAccessibilityService.h
@@ -39,17 +39,20 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsIAccessibilityService_h_
 #define _nsIAccessibilityService_h_
 
 #include "nsIAccessibleRetrieval.h"
 #include "nsIAccessibleEvent.h"
 
+#include "nsAutoPtr.h"
+
 class nsAccessible;
+class nsINode;
 class nsIContent;
 class nsIDocument;
 class nsIFrame;
 class nsIPresShell;
 class nsObjectFrame;
 
 // 10ff6dca-b219-4b64-9a4c-67a62b86edce
 #define NS_IACCESSIBILITYSERVICE_IID \
@@ -63,84 +66,73 @@ public:
 
   /**
    * Return an accessible object for a DOM node in the given pres shell.
    *
    * @param  aNode      [in] the DOM node to get an accessible for
    * @param  aPresShell [in] the presentation shell which contains layout info
    *                         for the DOM node
    */
-  virtual nsAccessible* GetAccessibleInShell(nsIDOMNode *aNode,
-                                             nsIPresShell *aPresShell) = 0;
+  virtual nsAccessible* GetAccessibleInShell(nsINode* aNode,
+                                             nsIPresShell* aPresShell) = 0;
 
   /**
    * Creates accessible for the given DOM node or frame.
    */
-  virtual nsresult CreateOuterDocAccessible(nsIDOMNode *aNode,
-                                            nsIAccessible **aAccessible) = 0;
-
-  virtual nsresult CreateHTML4ButtonAccessible(nsIFrame *aFrame,
-                                               nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHyperTextAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLBRAccessible(nsIFrame *aFrame,
-                                          nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLButtonAccessible(nsIFrame *aFrame,
-                                              nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLLIAccessible(nsIFrame *aFrame,
-                                          nsIFrame *aBulletFrame,
-                                          const nsAString& aBulletText,
-                                          nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLCheckboxAccessible(nsIFrame *aFrame,
-                                                nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLComboboxAccessible(nsIDOMNode *aNode,
-                                                nsIWeakReference *aPresShell,
-                                                nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLGenericAccessible(nsIFrame *aFrame,
-                                               nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLGroupboxAccessible(nsIFrame *aFrame,
-                                                nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLHRAccessible(nsIFrame *aFrame,
-                                          nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLImageAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLLabelAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLListboxAccessible(nsIDOMNode *aNode,
-                                               nsIWeakReference *aPresShell,
-                                               nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLMediaAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLObjectFrameAccessible(nsObjectFrame *aFrame,
-                                                   nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLRadioButtonAccessible(nsIFrame *aFrame,
-                                                   nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLSelectOptionAccessible(nsIDOMNode *aNode,
-                                                    nsIAccessible *aAccParent,
-                                                    nsIWeakReference *aPresShell,
-                                                    nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLTableAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLTableCellAccessible(nsIFrame *aFrame,
-                                                 nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLTextAccessible(nsIFrame *aFrame,
-                                            nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLTextFieldAccessible(nsIFrame *aFrame,
-                                                 nsIAccessible **aAccessible) = 0;
-  virtual nsresult CreateHTMLCaptionAccessible(nsIFrame *aFrame,
-                                               nsIAccessible **aAccessible) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLBRAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTML4ButtonAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLButtonAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLCaptionAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLCheckboxAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLComboboxAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLGroupboxAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLHRAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLImageAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLLabelAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLLIAccessible(nsIContent* aContent, nsIPresShell* aPresShell,
+                           const nsAString& aBulletText) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLListboxAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLMediaAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLObjectFrameAccessible(nsObjectFrame* aFrame, nsIContent* aContent,
+                                    nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLRadioButtonAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLTableAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLTableCellAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLTextAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLTextFieldAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateHyperTextAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
+  virtual already_AddRefed<nsAccessible>
+    CreateOuterDocAccessible(nsIContent* aContent, nsIPresShell* aPresShell) = 0;
 
   /**
    * Adds/remove ATK root accessible for gtk+ native window to/from children
    * of the application accessible.
    */
-  virtual nsresult AddNativeRootAccessible(void *aAtkAccessible,
-                                           nsIAccessible **aAccessible) = 0;
-  virtual nsresult
-    RemoveNativeRootAccessible(nsIAccessible *aRootAccessible) = 0;
+  virtual nsAccessible* AddNativeRootAccessible(void* aAtkAccessible) = 0;
+  virtual void RemoveNativeRootAccessible(nsAccessible* aRootAccessible) = 0;
 
   /**
    * Used to describe sort of changes leading to accessible tree invalidation.
    */
   enum {
     NODE_APPEND = 0x01,
     NODE_REMOVE = 0x02,
     NODE_SIGNIFICANT_CHANGE = 0x03,
--- a/accessible/src/atk/nsApplicationAccessibleWrap.cpp
+++ b/accessible/src/atk/nsApplicationAccessibleWrap.cpp
@@ -648,26 +648,23 @@ gboolean fireRootAccessibleAddedCB(gpoin
                           eventData->index, eventData->root_accessible, NULL);
     g_object_unref(eventData->app_accessible);
     g_object_unref(eventData->root_accessible);
     free(data);
     
     return FALSE;
 }
 
-nsresult
-nsApplicationAccessibleWrap::AddRootAccessible(nsIAccessible *aRootAccWrap)
+PRBool
+nsApplicationAccessibleWrap::AppendChild(nsAccessible *aChild)
 {
-    NS_ENSURE_ARG_POINTER(aRootAccWrap);
+    if (!nsApplicationAccessible::AppendChild(aChild))
+      return PR_FALSE;
 
-    // add by weak reference
-    nsresult rv = nsApplicationAccessible::AddRootAccessible(aRootAccWrap);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    AtkObject *atkAccessible = nsAccessibleWrap::GetAtkObject(aRootAccWrap);
+    AtkObject *atkAccessible = nsAccessibleWrap::GetAtkObject(aChild);
     atk_object_set_parent(atkAccessible, mAtkObject);
 
     PRUint32 count = mChildren.Length();
 
     // Emit children_changed::add in a timeout
     // to make sure aRootAccWrap is fully initialized.
     AtkRootAccessibleAddedEvent* eventData = (AtkRootAccessibleAddedEvent*)
       malloc(sizeof(AtkRootAccessibleAddedEvent));
@@ -675,32 +672,30 @@ nsApplicationAccessibleWrap::AddRootAcce
       eventData->app_accessible = mAtkObject;
       eventData->root_accessible = atkAccessible;
       eventData->index = count -1;
       g_object_ref(mAtkObject);
       g_object_ref(atkAccessible);
       g_timeout_add(0, fireRootAccessibleAddedCB, eventData);
     }
 
-    return NS_OK;
+    return PR_TRUE;
 }
 
-nsresult
-nsApplicationAccessibleWrap::RemoveRootAccessible(nsIAccessible *aRootAccWrap)
+PRBool
+nsApplicationAccessibleWrap::RemoveChild(nsAccessible* aChild)
 {
-    NS_ENSURE_ARG_POINTER(aRootAccWrap);
+    PRInt32 index = aChild->GetIndexInParent();
 
-    PRInt32 index = mChildren.IndexOf(aRootAccWrap);
-
-    AtkObject *atkAccessible = nsAccessibleWrap::GetAtkObject(aRootAccWrap);
+    AtkObject *atkAccessible = nsAccessibleWrap::GetAtkObject(aChild);
     atk_object_set_parent(atkAccessible, NULL);
     g_signal_emit_by_name(mAtkObject, "children_changed::remove", index,
                           atkAccessible, NULL);
 
-    return nsApplicationAccessible::RemoveRootAccessible(aRootAccWrap);
+    return nsApplicationAccessible::RemoveChild(aChild);
 }
 
 void
 nsApplicationAccessibleWrap::PreCreate()
 {
     if (!sATKChecked) {
         sATKLib = PR_LoadLibrary(sATKLibName);
         if (sATKLib) {
--- a/accessible/src/atk/nsApplicationAccessibleWrap.h
+++ b/accessible/src/atk/nsApplicationAccessibleWrap.h
@@ -52,17 +52,17 @@ public:
 
 public:
     nsApplicationAccessibleWrap();
     virtual ~nsApplicationAccessibleWrap();
 
     // nsAccessNode
     virtual PRBool Init();
 
+    // nsAccessible
+    virtual PRBool AppendChild(nsAccessible* aChild);
+    virtual PRBool RemoveChild(nsAccessible* aChild);
+
     // return the atk object for app root accessible
     NS_IMETHOD GetNativeInterface(void **aOutAccessible);
-
-    // nsApplicationAccessible
-    virtual nsresult AddRootAccessible(nsIAccessible *aRootAccWrap);
-    virtual nsresult RemoveRootAccessible(nsIAccessible *aRootAccWrap);
 };
 
 #endif   /* __NS_APP_ROOT_ACCESSIBLE_H__ */
--- a/accessible/src/base/nsAccDocManager.cpp
+++ b/accessible/src/base/nsAccDocManager.cpp
@@ -434,17 +434,17 @@ nsDocAccessible*
 nsAccDocManager::CreateDocOrRootAccessible(nsIDocument *aDocument)
 {
   // Ignore temporary, hiding and svg resource documents.
   if (aDocument->IsInitialDocument() || !aDocument->IsVisible() ||
       aDocument->GetDisplayDocument())
     return nsnull;
 
   // Ignore documents without presshell.
-  nsIPresShell *presShell = aDocument->GetPrimaryShell();
+  nsIPresShell *presShell = aDocument->GetShell();
   if (!presShell)
     return nsnull;
 
   // Do not create document accessible until role content is loaded, otherwise
   // we get accessible document with wrong role.
   nsIContent *rootElm = nsCoreUtils::GetRoleContent(aDocument);
   if (!rootElm)
     return nsnull;
--- a/accessible/src/base/nsAccDocManager.h
+++ b/accessible/src/base/nsAccDocManager.h
@@ -254,17 +254,17 @@ private:
   }                                                                            \
   printf("doc state: %s", docState);                                           \
   printf(", %sinitial", aDocument->IsInitialDocument() ? "" : "not ");         \
   printf(", %sshowing", aDocument->IsShowing() ? "" : "not ");                 \
   printf(", %svisible", aDocument->IsVisible() ? "" : "not ");                 \
   printf(", %sactive", aDocument->IsActive() ? "" : "not ");
 
 #define NS_LOG_ACCDOC_DOCPRESSHELL(aDocument)                                  \
-  nsIPresShell *ps = aDocument->GetPrimaryShell();                             \
+  nsIPresShell *ps = aDocument->GetShell();                                    \
   printf("presshell: %p", ps);                                                 \
   nsIScrollableFrame *sf = ps ?                                                \
     ps->GetRootScrollFrameAsScrollableExternal() : nsnull;                     \
   printf(", root scroll frame: %p", sf);
 
 #define NS_LOG_ACCDOC_DOCLOADGROUP(aDocument)                                  \
   nsCOMPtr<nsILoadGroup> loadGroup = aDocument->GetDocumentLoadGroup();        \
   printf("load group: %p", loadGroup);
--- a/accessible/src/base/nsAccUtils.cpp
+++ b/accessible/src/base/nsAccUtils.cpp
@@ -154,20 +154,20 @@ nsAccUtils::GetPositionAndSizeForXULSele
   control->GetIndexOfItem(item, &indexOf);
 
   *aSetSize = itemsCount;
   *aPosInSet = indexOf;
 
   for (PRUint32 index = 0; index < itemsCount; index++) {
     nsCOMPtr<nsIDOMXULSelectControlItemElement> currItem;
     control->GetItemAtIndex(index, getter_AddRefs(currItem));
-    nsCOMPtr<nsIDOMNode> currNode(do_QueryInterface(currItem));
+    nsCOMPtr<nsINode> currNode(do_QueryInterface(currItem));
 
-    nsCOMPtr<nsIAccessible> itemAcc;
-    GetAccService()->GetAccessibleFor(currNode, getter_AddRefs(itemAcc));
+    nsAccessible* itemAcc = GetAccService()->GetAccessible(currNode);
+
     if (!itemAcc ||
         State(itemAcc) & nsIAccessibleStates::STATE_INVISIBLE) {
       (*aSetSize)--;
       if (index < static_cast<PRUint32>(indexOf))
         (*aPosInSet)--;
     }
   }
 
@@ -196,19 +196,19 @@ nsAccUtils::GetPositionAndSizeForXULCont
   PRInt32 indexOf = 0;
   container->GetIndexOfItem(item, &indexOf);
 
   // Calculate set size and position in the set.
   *aSetSize = 0, *aPosInSet = 0;
   for (PRInt32 index = indexOf; index >= 0; index--) {
     nsCOMPtr<nsIDOMXULElement> item;
     container->GetItemAtIndex(index, getter_AddRefs(item));
+    nsCOMPtr<nsINode> itemNode(do_QueryInterface(item));
 
-    nsCOMPtr<nsIAccessible> itemAcc;
-    GetAccService()->GetAccessibleFor(item, getter_AddRefs(itemAcc));
+    nsAccessible* itemAcc = GetAccService()->GetAccessible(itemNode);
 
     if (itemAcc) {
       PRUint32 itemRole = Role(itemAcc);
       if (itemRole == nsIAccessibleRole::ROLE_SEPARATOR)
         break; // We reached the beginning of our group.
 
       PRUint32 itemState = State(itemAcc);
       if (!(itemState & nsIAccessibleStates::STATE_INVISIBLE)) {
@@ -217,19 +217,19 @@ nsAccUtils::GetPositionAndSizeForXULCont
       }
     }
   }
 
   for (PRInt32 index = indexOf + 1; index < static_cast<PRInt32>(itemsCount);
        index++) {
     nsCOMPtr<nsIDOMXULElement> item;
     container->GetItemAtIndex(index, getter_AddRefs(item));
+    nsCOMPtr<nsINode> itemNode(do_QueryInterface(item));
     
-    nsCOMPtr<nsIAccessible> itemAcc;
-    GetAccService()->GetAccessibleFor(item, getter_AddRefs(itemAcc));
+    nsAccessible* itemAcc = GetAccService()->GetAccessible(itemNode);
 
     if (itemAcc) {
       PRUint32 itemRole = Role(itemAcc);
       if (itemRole == nsIAccessibleRole::ROLE_SEPARATOR)
         break; // We reached the end of our group.
 
       PRUint32 itemState = State(itemAcc);
       if (!(itemState & nsIAccessibleStates::STATE_INVISIBLE))
--- a/accessible/src/base/nsAccessNode.h
+++ b/accessible/src/base/nsAccessNode.h
@@ -171,22 +171,16 @@ public:
     return GetNode() && GetNode()->IsNodeOfType(nsINode::eDOCUMENT);
   }
 
   /**
    * Return the corresponding press shell for this accessible.
    */
   already_AddRefed<nsIPresShell> GetPresShell();
 
-  /**
-   * Return true if the accessible still has presentation shell. Light-weight
-   * version of IsDefunct() method.
-   */
-  PRBool HasWeakShell() const { return !!mWeakShell; }
-
 protected:
     nsPresContext* GetPresContext();
 
     void LastRelease();
 
   nsCOMPtr<nsIContent> mContent;
   nsCOMPtr<nsIWeakReference> mWeakShell;
 
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -181,608 +181,289 @@ nsresult
 nsAccessibilityService::FireAccessibleEvent(PRUint32 aEvent,
                                             nsIAccessible *aTarget)
 {
   nsRefPtr<nsAccessible> accessible(do_QueryObject(aTarget));
   nsEventShell::FireEvent(aEvent, accessible);
   return NS_OK;
 }
 
-// nsAccessibilityService private
-nsresult
-nsAccessibilityService::GetInfo(nsIFrame *aFrame, nsIWeakReference **aShell,
-                                nsIContent **aContent)
-{
-  NS_ASSERTION(aFrame,"Error -- 1st argument (aFrame) is null!!");
-  if (!aFrame) {
-    return NS_ERROR_FAILURE;
-  }
-  nsIContent* content = aFrame->GetContent();
-  if (!content)
-    return NS_ERROR_FAILURE;
-
-  nsIDocument* document = content->GetOwnerDoc();
-  if (!document)
-    return NS_ERROR_FAILURE;
-
-  NS_ASSERTION(document->GetPrimaryShell(),"Error no shells!");
-
-  // do_GetWR only works into a |nsCOMPtr| :-(
-  nsCOMPtr<nsIWeakReference> weakShell =
-    do_GetWeakReference(document->GetPrimaryShell());
-
-  weakShell.forget(aShell);
-  NS_IF_ADDREF(*aContent = content);
-
-  return NS_OK;
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 // nsIAccessibilityService
 
-nsresult
-nsAccessibilityService::CreateOuterDocAccessible(nsIDOMNode* aDOMNode, 
-                                                 nsIAccessible **aOuterDocAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateOuterDocAccessible(nsIContent* aContent,
+                                                 nsIPresShell* aPresShell)
 {
-  NS_ENSURE_ARG_POINTER(aDOMNode);
-  
-  *aOuterDocAccessible = nsnull;
-
-  nsCOMPtr<nsIContent> content(do_QueryInterface(aDOMNode));
-  nsCOMPtr<nsIWeakReference> outerWeakShell =
-    nsCoreUtils::GetWeakShellFor(content);
-  NS_ENSURE_TRUE(outerWeakShell, NS_ERROR_FAILURE);
-
-  nsOuterDocAccessible *outerDocAccessible =
-    new nsOuterDocAccessible(content, outerWeakShell);
-  NS_ENSURE_TRUE(outerDocAccessible, NS_ERROR_FAILURE);
-
-  NS_ADDREF(*aOuterDocAccessible = outerDocAccessible);
-
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsOuterDocAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
- /**
-   * HTML widget creation
-   */
-nsresult
-nsAccessibilityService::CreateHTML4ButtonAccessible(nsIFrame *aFrame,
-                                                    nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTML4ButtonAccessible(nsIContent* aContent,
+                                                    nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTML4ButtonAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTML4ButtonAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLButtonAccessible(nsIFrame *aFrame,
-                                                   nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLButtonAccessible(nsIContent* aContent,
+                                                   nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLButtonAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLButtonAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-// nsAccessibilityService private
 already_AddRefed<nsAccessible>
-nsAccessibilityService::CreateHTMLAccessibleByMarkup(nsIFrame *aFrame,
-                                                     nsIWeakReference *aWeakShell,
-                                                     nsINode *aNode)
+nsAccessibilityService::CreateHTMLLIAccessible(nsIContent* aContent,
+                                               nsIPresShell* aPresShell,
+                                               const nsAString& aBulletText)
 {
-  // This method assumes we're in an HTML namespace.
-  nsRefPtr<nsAccessible> accessible;
-
-  nsCOMPtr<nsIContent> content(do_QueryInterface(aNode));
-  nsIAtom *tag = content->Tag();
-  if (tag == nsAccessibilityAtoms::legend) {
-    accessible = new nsHTMLLegendAccessible(content, aWeakShell);
-  }
-  else if (tag == nsAccessibilityAtoms::option) {
-    accessible = new nsHTMLSelectOptionAccessible(content, aWeakShell);
-  }
-  else if (tag == nsAccessibilityAtoms::optgroup) {
-    accessible = new nsHTMLSelectOptGroupAccessible(content, aWeakShell);
-  }
-  else if (tag == nsAccessibilityAtoms::ul || tag == nsAccessibilityAtoms::ol ||
-           tag == nsAccessibilityAtoms::dl) {
-    accessible = new nsHTMLListAccessible(content, aWeakShell);
-  }
-  else if (tag == nsAccessibilityAtoms::a) {
-
-    // Only some roles truly enjoy life as nsHTMLLinkAccessibles, for details
-    // see closed bug 494807.
-    nsRoleMapEntry *roleMapEntry = nsAccUtils::GetRoleMapEntry(aNode);
-    if (roleMapEntry && roleMapEntry->role != nsIAccessibleRole::ROLE_NOTHING
-        && roleMapEntry->role != nsIAccessibleRole::ROLE_LINK) {
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLLIAccessible(aContent, weakShell,
+                                                    aBulletText);
+  NS_IF_ADDREF(accessible);
+  return accessible;
+}
 
-      accessible = new nsHyperTextAccessibleWrap(content, aWeakShell);
-    } else {
-      accessible = new nsHTMLLinkAccessible(content, aWeakShell);
-    }
-  }
-  else if (tag == nsAccessibilityAtoms::dt ||
-           (tag == nsAccessibilityAtoms::li && 
-            aFrame->GetType() != nsAccessibilityAtoms::blockFrame)) {
-    // Normally for li, it is created by the list item frame (in nsBlockFrame)
-    // which knows about the bullet frame; however, in this case the list item
-    // must have been styled using display: foo
-    accessible = new nsHTMLLIAccessible(content, aWeakShell, EmptyString());
-  }
-  else if (tag == nsAccessibilityAtoms::abbr ||
-           tag == nsAccessibilityAtoms::acronym ||
-           tag == nsAccessibilityAtoms::blockquote ||
-           tag == nsAccessibilityAtoms::dd ||
-           tag == nsAccessibilityAtoms::form ||
-           tag == nsAccessibilityAtoms::h1 ||
-           tag == nsAccessibilityAtoms::h2 ||
-           tag == nsAccessibilityAtoms::h3 ||
-           tag == nsAccessibilityAtoms::h4 ||
-           tag == nsAccessibilityAtoms::h5 ||
-           tag == nsAccessibilityAtoms::h6 ||
-           tag == nsAccessibilityAtoms::q) {
-
-    accessible = new nsHyperTextAccessibleWrap(content, aWeakShell);
-  }
-  else if (tag == nsAccessibilityAtoms::tr) {
-    accessible = new nsEnumRoleAccessible(content, aWeakShell,
-                                          nsIAccessibleRole::ROLE_ROW);
-  }
-  else if (nsCoreUtils::IsHTMLTableHeader(content)) {
-    accessible = new nsHTMLTableHeaderCellAccessibleWrap(content, aWeakShell);
-  }
-
-  return accessible.forget();
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHyperTextAccessible(nsIContent* aContent,
+                                                  nsIPresShell* aPresShell)
+{
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHyperTextAccessibleWrap(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLLIAccessible(nsIFrame *aFrame, 
-                                               nsIFrame *aBulletFrame,
-                                               const nsAString& aBulletText,
-                                               nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLCheckboxAccessible(nsIContent* aContent,
+                                                     nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLLIAccessible(content, weakShell, aBulletText);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
-}
-
-nsresult
-nsAccessibilityService::CreateHyperTextAccessible(nsIFrame *aFrame,
-                                                  nsIAccessible **aAccessible)
-{
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHyperTextAccessibleWrap(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLCheckboxAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLCheckboxAccessible(nsIFrame *aFrame,
-                                                     nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLComboboxAccessible(nsIContent* aContent,
+                                                     nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLCheckboxAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLComboboxAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLComboboxAccessible(nsIDOMNode *aDOMNode,
-                                                     nsIWeakReference *aPresShell,
-                                                     nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLImageAccessible(nsIContent* aContent,
+                                                  nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content(do_QueryInterface(aDOMNode));
-  *aAccessible = new nsHTMLComboboxAccessible(content, aPresShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
-}
-
-nsresult
-nsAccessibilityService::CreateHTMLImageAccessible(nsIFrame *aFrame,
-                                                  nsIAccessible **aAccessible)
-{
-  NS_ENSURE_ARG_POINTER(aAccessible);
-  *aAccessible = nsnull;
-
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
   nsCOMPtr<nsIHTMLDocument> htmlDoc =
-    do_QueryInterface(content->GetCurrentDoc());
+    do_QueryInterface(aContent->GetCurrentDoc());
 
   nsCOMPtr<nsIDOMHTMLMapElement> mapElm;
   if (htmlDoc) {
     nsAutoString mapElmName;
-    content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::usemap,
-                     mapElmName);
+    aContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::usemap,
+                      mapElmName);
 
     if (!mapElmName.IsEmpty()) {
       if (mapElmName.CharAt(0) == '#')
         mapElmName.Cut(0,1);
       mapElm = htmlDoc->GetImageMap(mapElmName);
     }
   }
 
-  if (mapElm)
-    *aAccessible = new nsHTMLImageMapAccessible(content, weakShell, mapElm);
-  else
-    *aAccessible = new nsHTMLImageAccessibleWrap(content, weakShell);
-
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
-}
-
-nsresult
-nsAccessibilityService::CreateHTMLGenericAccessible(nsIFrame *aFrame, nsIAccessible **aAccessible)
-{
-  return CreateHyperTextAccessible(aFrame, aAccessible);
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = mapElm ?
+    new nsHTMLImageMapAccessible(aContent, weakShell, mapElm) :
+    new nsHTMLImageAccessibleWrap(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLGroupboxAccessible(nsIFrame *aFrame,
-                                                     nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLGroupboxAccessible(nsIContent* aContent,
+                                                     nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLGroupboxAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
+}
 
-  *aAccessible = new nsHTMLGroupboxAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLListboxAccessible(nsIContent* aContent,
+                                                    nsIPresShell* aPresShell)
+{
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLSelectListAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLListboxAccessible(nsIDOMNode* aDOMNode,
-                                                    nsIWeakReference *aPresShell,
-                                                    nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLMediaAccessible(nsIContent* aContent,
+                                                  nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content(do_QueryInterface(aDOMNode));
-  *aAccessible = new nsHTMLSelectListAccessible(content, aPresShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsEnumRoleAccessible(aContent, weakShell,
+                                                      nsIAccessibleRole::ROLE_GROUPING);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLMediaAccessible(nsIFrame *aFrame,
-                                                  nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLObjectFrameAccessible(nsObjectFrame* aFrame,
+                                                        nsIContent* aContent,
+                                                        nsIPresShell* aPresShell)
 {
-  NS_ENSURE_ARG_POINTER(aAccessible);
-  *aAccessible = nsnull;
-
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  *aAccessible = new nsEnumRoleAccessible(content, weakShell,
-                                          nsIAccessibleRole::ROLE_GROUPING);
-  NS_ENSURE_TRUE(*aAccessible, NS_ERROR_OUT_OF_MEMORY);
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
-}
+  // We can have several cases here:
+  // 1) a text or html embedded document where the contentDocument variable in
+  //    the object element holds the content;
+  // 2) web content that uses a plugin, which means we will have to go to
+  //    the plugin to get the accessible content;
+  // 3) an image or imagemap, where the image frame points back to the object
+  //    element DOMNode.
 
-/**
-  * We can have several cases here. 
-  *  1) a text or html embedded document where the contentDocument
-  *     variable in the object element holds the content
-  *  2) web content that uses a plugin, which means we will
-  *     have to go to the plugin to get the accessible content
-  *  3) An image or imagemap, where the image frame points back to 
-  *     the object element DOMNode
-  */
-nsresult
-nsAccessibilityService::CreateHTMLObjectFrameAccessible(nsObjectFrame *aFrame,
-                                                        nsIAccessible **aAccessible)
-{
-  NS_ENSURE_ARG_POINTER(aAccessible);
-  *aAccessible = nsnull;
+  if (aFrame->GetRect().IsEmpty())
+    return nsnull;
 
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  GetInfo(aFrame, getter_AddRefs(weakShell), getter_AddRefs(content));
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
 
-  if (aFrame->GetRect().IsEmpty()) {
-    return NS_ERROR_FAILURE;
-  }
   // 1) for object elements containing either HTML or TXT documents
-  nsCOMPtr<nsIDOMHTMLObjectElement> obj(do_QueryInterface(content));
+  nsCOMPtr<nsIDOMHTMLObjectElement> obj(do_QueryInterface(aContent));
   if (obj) {
     nsCOMPtr<nsIDOMDocument> domDoc;
     obj->GetContentDocument(getter_AddRefs(domDoc));
-    if (domDoc) {
-      nsCOMPtr<nsIDOMNode> DOMNode(do_QueryInterface(content));
-      return CreateOuterDocAccessible(DOMNode, aAccessible);
-    }
+    if (domDoc)
+      return CreateOuterDocAccessible(aContent, aPresShell);
   }
 
 #ifdef XP_WIN
   // 2) for plugins
   nsCOMPtr<nsIPluginInstance> pluginInstance ;
   aFrame->GetPluginInstance(*getter_AddRefs(pluginInstance));
   if (pluginInstance) {
     // Note: pluginPort will be null if windowless.
     HWND pluginPort = nsnull;
     aFrame->GetPluginPort(&pluginPort);
 
-    *aAccessible =
-      new nsHTMLWin32ObjectOwnerAccessible(content, weakShell, pluginPort);
-    NS_ENSURE_TRUE(*aAccessible, NS_ERROR_OUT_OF_MEMORY);
-
-    NS_ADDREF(*aAccessible);
-    return NS_OK;
+    nsAccessible* accessible = new nsHTMLWin32ObjectOwnerAccessible(aContent,
+                                                                    weakShell,
+                                                                    pluginPort);
+    NS_IF_ADDREF(accessible);
+    return accessible;
   }
 #endif
 
   // 3) for images and imagemaps, or anything else with a child frame
   // we have the object frame, get the image frame
-  nsIFrame *frame = aFrame->GetFirstChild(nsnull);
-  if (frame)
-    return frame->GetAccessible(aAccessible);
-
-  return NS_OK;
+  nsIFrame* frame = aFrame->GetFirstChild(nsnull);
+  return frame ? frame->CreateAccessible() : nsnull;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLRadioButtonAccessible(nsIFrame *aFrame,
-                                                        nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLRadioButtonAccessible(nsIContent* aContent,
+                                                        nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLRadioButtonAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLRadioButtonAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLSelectOptionAccessible(nsIDOMNode *aDOMNode,
-                                                         nsIAccessible *aParent, 
-                                                         nsIWeakReference *aPresShell,
-                                                         nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLTableAccessible(nsIContent* aContent,
+                                                  nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content(do_QueryInterface(aDOMNode));
-  *aAccessible = new nsHTMLSelectOptionAccessible(content, aPresShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLTableAccessibleWrap(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLTableAccessible(nsIFrame *aFrame,
-                                                  nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLTableCellAccessible(nsIContent* aContent,
+                                                      nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLTableAccessibleWrap(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLTableCellAccessibleWrap(aContent,
+                                                               weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLTableCellAccessible(nsIFrame *aFrame,
-                                                      nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLTextAccessible(nsIContent* aContent,
+                                                 nsIPresShell* aPresShell)
 {
-  NS_ENSURE_ARG_POINTER(aAccessible);
-  *aAccessible = nsnull;
-
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLTableCellAccessibleWrap(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLTextAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLTextAccessible(nsIFrame *aFrame,
-                                                 nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLTextFieldAccessible(nsIContent* aContent,
+                                                      nsIPresShell* aPresShell)
 {
-  *aAccessible = nsnull;
-
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  // XXX Don't create ATK objects for these
-  *aAccessible = new nsHTMLTextAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLTextFieldAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLTextFieldAccessible(nsIFrame *aFrame,
-                                                      nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLLabelAccessible(nsIContent* aContent,
+                                                  nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLTextFieldAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLLabelAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLLabelAccessible(nsIFrame *aFrame,
-                                                  nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLHRAccessible(nsIContent* aContent,
+                                               nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLLabelAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLHRAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLHRAccessible(nsIFrame *aFrame,
-                                               nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLBRAccessible(nsIContent* aContent,
+                                               nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLHRAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLBRAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
-nsresult
-nsAccessibilityService::CreateHTMLBRAccessible(nsIFrame *aFrame,
-                                               nsIAccessible **aAccessible)
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLCaptionAccessible(nsIContent* aContent,
+                                                    nsIPresShell* aPresShell)
 {
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLBRAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
-}
-
-nsresult
-nsAccessibilityService::CreateHTMLCaptionAccessible(nsIFrame *aFrame,
-                                                    nsIAccessible **aAccessible)
-{
-  nsCOMPtr<nsIContent> content;
-  nsCOMPtr<nsIWeakReference> weakShell;
-  nsresult rv = GetInfo(aFrame, getter_AddRefs(weakShell),
-                        getter_AddRefs(content));
-  if (NS_FAILED(rv))
-    return rv;
-
-  *aAccessible = new nsHTMLCaptionAccessible(content, weakShell);
-  if (!*aAccessible)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  NS_ADDREF(*aAccessible);
-  return NS_OK;
+  nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
+  nsAccessible* accessible = new nsHTMLCaptionAccessible(aContent, weakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
 void
 nsAccessibilityService::PresShellDestroyed(nsIPresShell *aPresShell)
 {
   // Presshell destruction will automatically destroy shells for descendant
   // documents, so no need to worry about those. Just shut down the accessible
   // for this one document. That keeps us from having bad behavior in case of
@@ -1037,26 +718,25 @@ nsAccessibilityService::GetAccessibleFro
   }
 
   NS_IF_ADDREF(*aAccessible = accessible);
   return NS_OK;
 }
 
 // nsIAccesibilityService
 nsAccessible*
-nsAccessibilityService::GetAccessibleInShell(nsIDOMNode *aNode, 
-                                             nsIPresShell *aPresShell) 
+nsAccessibilityService::GetAccessibleInShell(nsINode* aNode,
+                                             nsIPresShell* aPresShell)
 {
   if (!aNode || !aPresShell)
     return nsnull;
 
-  nsCOMPtr<nsINode> node(do_QueryInterface(aNode));
   nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
   nsRefPtr<nsAccessible> accessible =
-    GetAccessible(node, aPresShell, weakShell);
+    GetAccessible(aNode, aPresShell, weakShell);
   return accessible;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessibilityService public
 
 nsAccessible *
 nsAccessibilityService::GetAccessible(nsINode *aNode)
@@ -1093,17 +773,17 @@ nsAccessibilityService::GetContainerAcce
 {
   if (!aNode)
     return nsnull;
 
   nsIDocument *document = aNode->GetCurrentDoc();
   if (!document)
     return nsnull;
 
-  nsIPresShell *presShell = document->GetPrimaryShell();
+  nsIPresShell *presShell = document->GetShell();
   if (!presShell)
     return nsnull;
 
   nsINode *currNode = aNode;
   nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(presShell));
 
   nsAccessible *accessible = nsnull;
   while (!accessible && (currNode = currNode->GetNodeParent())) {
@@ -1243,17 +923,20 @@ nsAccessibilityService::GetAccessible(ns
   }
 
   if (weakFrame.GetFrame()->GetContent() != content) {
     // Not the main content for this frame. This happens because <area>
     // elements return the image frame as their primary frame. The main content
     // for the image frame is the image content. If the frame is not an image
     // frame or the node is not an area element then null is returned.
     // This setup will change when bug 135040 is fixed.
-    return GetAreaAccessible(weakFrame.GetFrame(), aNode, aWeakShell);
+    nsAccessible* areaAcc = GetAreaAccessible(weakFrame.GetFrame(),
+                                              aNode, aWeakShell);
+    NS_IF_ADDREF(areaAcc);
+    return areaAcc;
   }
 
   // Attempt to create an accessible based on what we know.
   nsRefPtr<nsAccessible> newAcc;
   if (content->IsNodeOfType(nsINode::eTEXT)) {
     // --- Create HTML for visible text frames ---
     nsIFrame* f = weakFrame.GetFrame();
     if (f && f->IsEmpty()) {
@@ -1263,24 +946,20 @@ nsAccessibilityService::GetAccessible(ns
         // Really empty -- nothing is rendered
         if (aIsHidden)
           *aIsHidden = PR_TRUE;
 
         return nsnull;
       }
     }
     if (weakFrame.IsAlive()) {
-      nsCOMPtr<nsIAccessible> newAccessible;
-      weakFrame.GetFrame()->GetAccessible(getter_AddRefs(newAccessible));
-      if (newAccessible) {
-        newAcc = do_QueryObject(newAccessible);
-        if (InitAccessible(newAcc, nsnull))
-          return newAcc.forget();
-        return nsnull;
-      }
+      newAcc = weakFrame.GetFrame()->CreateAccessible();
+      if (InitAccessible(newAcc, nsnull))
+        return newAcc.forget();
+      return nsnull;
     }
 
     return nsnull;
   }
 
   PRBool isHTML = content->IsHTML();
   if (isHTML && content->Tag() == nsAccessibilityAtoms::map) {
     // Create hyper text accessible for HTML map if it is used to group links
@@ -1406,18 +1085,18 @@ nsAccessibilityService::GetAccessible(ns
     }
 
     if (!newAcc && tryTagNameOrFrame) {
       // Prefer to use markup (mostly tag name, perhaps attributes) to
       // decide if and what kind of accessible to create.
       // The method creates accessibles for table related content too therefore
       // we do not call it if accessibles for table related content are
       // prevented above.
-      newAcc = CreateHTMLAccessibleByMarkup(weakFrame.GetFrame(), aWeakShell,
-                                            aNode);
+      newAcc = CreateHTMLAccessibleByMarkup(weakFrame.GetFrame(), content,
+                                            aWeakShell);
 
       if (!newAcc) {
         // Do not create accessible object subtrees for non-rendered table
         // captions. This could not be done in
         // nsTableCaptionFrame::GetAccessible() because the descendants of
         // the table caption would still be created. By setting
         // *aIsHidden = PR_TRUE we ensure that no descendant accessibles are
         // created.
@@ -1431,19 +1110,17 @@ nsAccessibilityService::GetAccessible(ns
           // is no better place:
           if (aIsHidden)
             *aIsHidden = PR_TRUE;
 
           return nsnull;
         }
 
         // Try using frame to do it.
-        nsCOMPtr<nsIAccessible> newAccessible;
-        f->GetAccessible(getter_AddRefs(newAccessible));
-        newAcc = do_QueryObject(newAccessible);
+        newAcc = f->CreateAccessible();
       }
     }
   }
 
   if (!newAcc) {
     // Elements may implement nsIAccessibleProvider via XBL. This allows them to
     // say what kind of accessible to create.
     newAcc = CreateAccessibleByType(content, aWeakShell);
@@ -1623,17 +1300,17 @@ nsAccessibilityService::GetRelevantConte
           return bindingParent;
       }
     }
   }
 
   return aNode;
 }
 
-already_AddRefed<nsAccessible>
+nsAccessible*
 nsAccessibilityService::GetAreaAccessible(nsIFrame *aImageFrame,
                                           nsINode *aAreaNode,
                                           nsIWeakReference *aWeakShell)
 {
   // Check if frame is an image frame, and content is <area>.
   nsIImageFrame *imageFrame = do_QueryFrame(aImageFrame);
   if (!imageFrame)
     return nsnull;
@@ -1642,309 +1319,449 @@ nsAccessibilityService::GetAreaAccessibl
   if (!areaElmt)
     return nsnull;
 
   // Try to get image map accessible from the global cache or create it
   // if failed.
   nsRefPtr<nsAccessible> imageAcc =
     GetCachedAccessible(aImageFrame->GetContent(), aWeakShell);
   if (!imageAcc) {
-    nsCOMPtr<nsIAccessible> imageAccessible;
-    CreateHTMLImageAccessible(aImageFrame,
-                              getter_AddRefs(imageAccessible));
+    imageAcc = CreateHTMLImageAccessible(aImageFrame->GetContent(),
+                                         aImageFrame->PresContext()->PresShell());
 
-    imageAcc = do_QueryObject(imageAccessible);
     if (!InitAccessible(imageAcc, nsnull))
       return nsnull;
   }
 
   // Make sure <area> accessible children of the image map are cached so
   // that they should be available in global cache.
   imageAcc->EnsureChildren();
 
-  nsAccessible *cachedAreaAcc = GetCachedAccessible(aAreaNode, aWeakShell);
-  NS_IF_ADDREF(cachedAreaAcc);
-  return cachedAreaAcc;
+  return GetCachedAccessible(aAreaNode, aWeakShell);
 }
 
 already_AddRefed<nsAccessible>
-nsAccessibilityService::CreateAccessibleByType(nsIContent *aContent,
-                                               nsIWeakReference *aWeakShell)
+nsAccessibilityService::CreateAccessibleByType(nsIContent* aContent,
+                                               nsIWeakReference* aWeakShell)
 {
   nsCOMPtr<nsIAccessibleProvider> accessibleProvider(do_QueryInterface(aContent));
   if (!accessibleProvider)
     return nsnull;
 
   PRInt32 type;
   nsresult rv = accessibleProvider->GetAccessibleType(&type);
   if (NS_FAILED(rv))
     return nsnull;
 
-  nsRefPtr<nsAccessible> accessible;
   if (type == nsIAccessibleProvider::OuterDoc) {
-    accessible = new nsOuterDocAccessible(aContent, aWeakShell);
-    return accessible.forget();
+    nsAccessible* accessible = new nsOuterDocAccessible(aContent, aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
   }
 
+  nsAccessible* accessible = nsnull;
   switch (type)
   {
 #ifdef MOZ_XUL
     case nsIAccessibleProvider::NoAccessible:
       return nsnull;
 
     // XUL controls
     case nsIAccessibleProvider::XULAlert:
       accessible = new nsXULAlertAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULButton:
       accessible = new nsXULButtonAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULCheckbox:
       accessible = new nsXULCheckboxAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULColorPicker:
       accessible = new nsXULColorPickerAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULColorPickerTile:
       accessible = new nsXULColorPickerTileAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULCombobox:
       accessible = new nsXULComboboxAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULDropmarker:
       accessible = new nsXULDropmarkerAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULGroupbox:
       accessible = new nsXULGroupboxAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULImage:
     {
       // Don't include nameless images in accessible tree.
       if (!aContent->HasAttr(kNameSpaceID_None,
                              nsAccessibilityAtoms::tooltiptext))
         return nsnull;
 
       accessible = new nsHTMLImageAccessibleWrap(aContent, aWeakShell);
       break;
+
     }
     case nsIAccessibleProvider::XULLink:
       accessible = new nsXULLinkAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULListbox:
       accessible = new nsXULListboxAccessibleWrap(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULListCell:
       accessible = new nsXULListCellAccessibleWrap(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULListHead:
       accessible = new nsXULColumnsAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULListHeader:
       accessible = new nsXULColumnItemAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULListitem:
       accessible = new nsXULListitemAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULMenubar:
       accessible = new nsXULMenubarAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULMenuitem:
       accessible = new nsXULMenuitemAccessibleWrap(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULMenupopup:
     {
 #ifdef MOZ_ACCESSIBILITY_ATK
       // ATK considers this node to be redundant when within menubars, and it makes menu
       // navigation with assistive technologies more difficult
       // XXX In the future we will should this for consistency across the nsIAccessible
       // implementations on each platform for a consistent scripting environment, but
       // then strip out redundant accessibles in the nsAccessibleWrap class for each platform.
       nsIContent *parent = aContent->GetParent();
       if (parent && parent->NodeInfo()->Equals(nsAccessibilityAtoms::menu,
                                                kNameSpaceID_XUL))
         return nsnull;
 #endif
       accessible = new nsXULMenupopupAccessible(aContent, aWeakShell);
       break;
+
     }
     case nsIAccessibleProvider::XULMenuSeparator:
       accessible = new nsXULMenuSeparatorAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULPane:
       accessible = new nsEnumRoleAccessible(aContent, aWeakShell,
                                             nsIAccessibleRole::ROLE_PANE);
       break;
+
     case nsIAccessibleProvider::XULProgressMeter:
       accessible = new nsXULProgressMeterAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULStatusBar:
       accessible = new nsXULStatusBarAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULScale:
       accessible = new nsXULSliderAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULRadioButton:
       accessible = new nsXULRadioButtonAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULRadioGroup:
       accessible = new nsXULRadioGroupAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULTab:
       accessible = new nsXULTabAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULTabs:
       accessible = new nsXULTabsAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULTabpanels:
       accessible = new nsXULTabpanelsAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULText:
       accessible = new nsXULTextAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULTextBox:
       accessible = new nsXULTextFieldAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULThumb:
       accessible = new nsXULThumbAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULTree:
       return CreateAccessibleForXULTree(aContent, aWeakShell);
 
     case nsIAccessibleProvider::XULTreeColumns:
       accessible = new nsXULTreeColumnsAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULTreeColumnItem:
       accessible = new nsXULColumnItemAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULToolbar:
       accessible = new nsXULToolbarAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULToolbarSeparator:
       accessible = new nsXULToolbarSeparatorAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULTooltip:
       accessible = new nsXULTooltipAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XULToolbarButton:
       accessible = new nsXULToolbarButtonAccessible(aContent, aWeakShell);
       break;
+
 #endif // MOZ_XUL
 
 #ifndef DISABLE_XFORMS_HOOKS
     // XForms elements
     case nsIAccessibleProvider::XFormsContainer:
       accessible = new nsXFormsContainerAccessible(aContent, aWeakShell);
       break;
 
     case nsIAccessibleProvider::XFormsLabel:
       accessible = new nsXFormsLabelAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsOutput:
       accessible = new nsXFormsOutputAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsTrigger:
       accessible = new nsXFormsTriggerAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsInput:
       accessible = new nsXFormsInputAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsInputBoolean:
       accessible = new nsXFormsInputBooleanAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsInputDate:
       accessible = new nsXFormsInputDateAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsSecret:
       accessible = new nsXFormsSecretAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsSliderRange:
       accessible = new nsXFormsRangeAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsSelect:
       accessible = new nsXFormsSelectAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsChoices:
       accessible = new nsXFormsChoicesAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsSelectFull:
       accessible = new nsXFormsSelectFullAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsItemCheckgroup:
       accessible = new nsXFormsItemCheckgroupAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsItemRadiogroup:
       accessible = new nsXFormsItemRadiogroupAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsSelectCombobox:
       accessible = new nsXFormsSelectComboboxAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsItemCombobox:
       accessible = new nsXFormsItemComboboxAccessible(aContent, aWeakShell);
       break;
 
     case nsIAccessibleProvider::XFormsDropmarkerWidget:
       accessible = new nsXFormsDropmarkerWidgetAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsCalendarWidget:
       accessible = new nsXFormsCalendarWidgetAccessible(aContent, aWeakShell);
       break;
+
     case nsIAccessibleProvider::XFormsComboboxPopupWidget:
       accessible = new nsXFormsComboboxPopupWidgetAccessible(aContent, aWeakShell);
       break;
+
 #endif
 
     default:
       return nsnull;
   }
 
-  return accessible.forget();
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 
+already_AddRefed<nsAccessible>
+nsAccessibilityService::CreateHTMLAccessibleByMarkup(nsIFrame* aFrame,
+                                                     nsIContent* aContent,
+                                                     nsIWeakReference* aWeakShell)
+{
+  // This method assumes we're in an HTML namespace.
+  nsIAtom *tag = aContent->Tag();
+  if (tag == nsAccessibilityAtoms::legend) {
+    nsAccessible* accessible = new nsHTMLLegendAccessible(aContent, aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  if (tag == nsAccessibilityAtoms::option) {
+    nsAccessible* accessible = new nsHTMLSelectOptionAccessible(aContent,
+                                                                aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  if (tag == nsAccessibilityAtoms::optgroup) {
+    nsAccessible* accessible = new nsHTMLSelectOptGroupAccessible(aContent,
+                                                                  aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  if (tag == nsAccessibilityAtoms::ul || tag == nsAccessibilityAtoms::ol ||
+      tag == nsAccessibilityAtoms::dl) {
+    nsAccessible* accessible = new nsHTMLListAccessible(aContent, aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  if (tag == nsAccessibilityAtoms::a) {
+    // Only some roles truly enjoy life as nsHTMLLinkAccessibles, for details
+    // see closed bug 494807.
+    nsRoleMapEntry *roleMapEntry = nsAccUtils::GetRoleMapEntry(aContent);
+    if (roleMapEntry && roleMapEntry->role != nsIAccessibleRole::ROLE_NOTHING &&
+        roleMapEntry->role != nsIAccessibleRole::ROLE_LINK) {
+      nsAccessible* accessible = new nsHyperTextAccessibleWrap(aContent,
+                                                               aWeakShell);
+      NS_IF_ADDREF(accessible);
+      return accessible;
+    }
+
+    nsAccessible* accessible = new nsHTMLLinkAccessible(aContent, aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  if (tag == nsAccessibilityAtoms::dt ||
+      (tag == nsAccessibilityAtoms::li &&
+       aFrame->GetType() != nsAccessibilityAtoms::blockFrame)) {
+    // Normally for li, it is created by the list item frame (in nsBlockFrame)
+    // which knows about the bullet frame; however, in this case the list item
+    // must have been styled using display: foo
+    nsAccessible* accessible = new nsHTMLLIAccessible(aContent, aWeakShell,
+                                                      EmptyString());
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  if (tag == nsAccessibilityAtoms::abbr ||
+      tag == nsAccessibilityAtoms::acronym ||
+      tag == nsAccessibilityAtoms::blockquote ||
+      tag == nsAccessibilityAtoms::dd ||
+      tag == nsAccessibilityAtoms::form ||
+      tag == nsAccessibilityAtoms::h1 ||
+      tag == nsAccessibilityAtoms::h2 ||
+      tag == nsAccessibilityAtoms::h3 ||
+      tag == nsAccessibilityAtoms::h4 ||
+      tag == nsAccessibilityAtoms::h5 ||
+      tag == nsAccessibilityAtoms::h6 ||
+      tag == nsAccessibilityAtoms::q) {
+    nsAccessible* accessible = new nsHyperTextAccessibleWrap(aContent, aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  if (tag == nsAccessibilityAtoms::tr) {
+    nsAccessible* accessible = new nsEnumRoleAccessible(aContent, aWeakShell,
+                                                        nsIAccessibleRole::ROLE_ROW);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  if (nsCoreUtils::IsHTMLTableHeader(aContent)) {
+    nsAccessible* accessible = new nsHTMLTableHeaderCellAccessibleWrap(aContent,
+                                                                       aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  return nsnull;
+ }
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsIAccessibilityService (DON'T put methods here)
 
-nsresult
-nsAccessibilityService::AddNativeRootAccessible(void *aAtkAccessible,
-                                                nsIAccessible **aRootAccessible)
+nsAccessible*
+nsAccessibilityService::AddNativeRootAccessible(void* aAtkAccessible)
+ {
+#ifdef MOZ_ACCESSIBILITY_ATK
+  nsApplicationAccessible* applicationAcc =
+    nsAccessNode::GetApplicationAccessible();
+  if (!applicationAcc)
+    return nsnull;
+
+  nsNativeRootAccessibleWrap* nativeRootAcc =
+     new nsNativeRootAccessibleWrap((AtkObject*)aAtkAccessible);
+  if (!nativeRootAcc)
+    return nsnull;
+
+  if (applicationAcc->AppendChild(nativeRootAcc))
+    return nativeRootAcc;
+#endif
+
+  return nsnull;
+ }
+
+void
+nsAccessibilityService::RemoveNativeRootAccessible(nsAccessible* aAccessible)
 {
 #ifdef MOZ_ACCESSIBILITY_ATK
-  nsNativeRootAccessibleWrap* rootAccWrap =
-    new nsNativeRootAccessibleWrap((AtkObject*)aAtkAccessible);
-
-  *aRootAccessible = static_cast<nsIAccessible*>(rootAccWrap);
-  NS_ADDREF(*aRootAccessible);
-
-  nsApplicationAccessible *applicationAcc =
+  nsApplicationAccessible* applicationAcc =
     nsAccessNode::GetApplicationAccessible();
-  NS_ENSURE_STATE(applicationAcc);
-
-  applicationAcc->AddRootAccessible(*aRootAccessible);
 
-  return NS_OK;
-#else
-  return NS_ERROR_NOT_IMPLEMENTED;
-#endif
-}
-
-nsresult
-nsAccessibilityService::RemoveNativeRootAccessible(nsIAccessible *aRootAccessible)
-{
-#ifdef MOZ_ACCESSIBILITY_ATK
-  void* atkAccessible;
-  aRootAccessible->GetNativeInterface(&atkAccessible);
-
-  nsApplicationAccessible *applicationAcc =
-    nsAccessNode::GetApplicationAccessible();
-  NS_ENSURE_STATE(applicationAcc);
-
-  applicationAcc->RemoveRootAccessible(aRootAccessible);
-
-  return NS_OK;
-#else
-  return NS_ERROR_NOT_IMPLEMENTED;
+  if (applicationAcc)
+    applicationAcc->RemoveChild(aAccessible);
 #endif
 }
 
 // Called from layout when the frame tree owned by a node changes significantly
 nsresult
 nsAccessibilityService::InvalidateSubtreeFor(nsIPresShell *aShell,
                                              nsIContent *aChangeContent,
                                              PRUint32 aChangeType)
@@ -1998,62 +1815,68 @@ NS_GetAccessibilityService(nsIAccessibil
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessibilityService private (DON'T put methods here)
 
 already_AddRefed<nsAccessible>
 nsAccessibilityService::CreateAccessibleForDeckChild(nsIFrame* aFrame,
-                                                     nsIContent *aContent,
-                                                     nsIWeakReference *aWeakShell)
+                                                     nsIContent* aContent,
+                                                     nsIWeakReference* aWeakShell)
 {
-  nsRefPtr<nsAccessible> accessible;
-
   if (aFrame->GetType() == nsAccessibilityAtoms::boxFrame ||
       aFrame->GetType() == nsAccessibilityAtoms::scrollFrame) {
 
     nsIFrame* parentFrame = aFrame->GetParent();
     if (parentFrame && parentFrame->GetType() == nsAccessibilityAtoms::deckFrame) {
       // If deck frame is for xul:tabpanels element then the given node has
       // tabpanel accessible.
       nsCOMPtr<nsIContent> parentContent = parentFrame->GetContent();
 #ifdef MOZ_XUL
       if (parentContent->NodeInfo()->Equals(nsAccessibilityAtoms::tabpanels,
                                             kNameSpaceID_XUL)) {
-        accessible = new nsXULTabpanelAccessible(aContent, aWeakShell);
-      } else
+        nsAccessible* accessible = new nsXULTabpanelAccessible(aContent,
+                                                               aWeakShell);
+        NS_IF_ADDREF(accessible);
+        return accessible;
+      }
 #endif
-        accessible =
-          new nsEnumRoleAccessible(aContent, aWeakShell,
-                                   nsIAccessibleRole::ROLE_PROPERTYPAGE);
+      nsAccessible* accessible = new nsEnumRoleAccessible(aContent, aWeakShell,
+                                                          nsIAccessibleRole::ROLE_PROPERTYPAGE);
+      NS_IF_ADDREF(accessible);
+      return accessible;
     }
   }
 
-  return accessible.forget();
+  return nsnull;
 }
 
 #ifdef MOZ_XUL
 already_AddRefed<nsAccessible>
-nsAccessibilityService::CreateAccessibleForXULTree(nsIContent *aContent,
-                                                   nsIWeakReference *aWeakShell)
+nsAccessibilityService::CreateAccessibleForXULTree(nsIContent* aContent,
+                                                   nsIWeakReference* aWeakShell)
 {
   nsCOMPtr<nsITreeBoxObject> treeBoxObj = nsCoreUtils::GetTreeBoxObject(aContent);
   if (!treeBoxObj)
     return nsnull;
 
   nsCOMPtr<nsITreeColumns> treeColumns;
   treeBoxObj->GetColumns(getter_AddRefs(treeColumns));
   if (!treeColumns)
     return nsnull;
 
-  nsRefPtr<nsAccessible> accessible;
-
   PRInt32 count = 0;
   treeColumns->GetCount(&count);
-  if (count == 1) // outline of list accessible
-    accessible = new nsXULTreeAccessible(aContent, aWeakShell);
-  else // table or tree table accessible
-    accessible = new nsXULTreeGridAccessibleWrap(aContent, aWeakShell);
 
-  return accessible.forget();
+  // Outline of list accessible.
+  if (count == 1) {
+    nsAccessible* accessible = new nsXULTreeAccessible(aContent, aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
+  // Table or tree table accessible.
+  nsAccessible* accessible = new nsXULTreeGridAccessibleWrap(aContent, aWeakShell);
+  NS_IF_ADDREF(accessible);
+  return accessible;
 }
 #endif
--- a/accessible/src/base/nsAccessibilityService.h
+++ b/accessible/src/base/nsAccessibilityService.h
@@ -53,75 +53,66 @@ class nsAccessibilityService : public ns
 public:
   virtual ~nsAccessibilityService();
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLERETRIEVAL
   NS_DECL_NSIOBSERVER
 
   // nsIAccessibilityService
-  virtual nsAccessible* GetAccessibleInShell(nsIDOMNode *aNode,
-                                             nsIPresShell *aPresShell);
+  virtual nsAccessible* GetAccessibleInShell(nsINode* aNode,
+                                             nsIPresShell* aPresShell);
 
-  virtual nsresult CreateOuterDocAccessible(nsIDOMNode *aNode,
-                                            nsIAccessible **aAccessible);
-  virtual nsresult CreateHTML4ButtonAccessible(nsIFrame *aFrame,
-                                               nsIAccessible **aAccessible);
-  virtual nsresult CreateHyperTextAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLBRAccessible(nsIFrame *aFrame,
-                                          nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLButtonAccessible(nsIFrame *aFrame,
-                                              nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLLIAccessible(nsIFrame *aFrame,
-                                          nsIFrame *aBulletFrame,
-                                          const nsAString& aBulletText,
-                                          nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLCheckboxAccessible(nsIFrame *aFrame,
-                                                nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLComboboxAccessible(nsIDOMNode *aNode,
-                                                nsIWeakReference *aPresShell,
-                                                nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLGenericAccessible(nsIFrame *aFrame,
-                                               nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLGroupboxAccessible(nsIFrame *aFrame,
-                                                nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLHRAccessible(nsIFrame *aFrame,
-                                          nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLImageAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLLabelAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLListboxAccessible(nsIDOMNode *aNode,
-                                               nsIWeakReference *aPresShell,
-                                               nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLMediaAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLObjectFrameAccessible(nsObjectFrame *aFrame,
-                                                   nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLRadioButtonAccessible(nsIFrame *aFrame,
-                                                   nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLSelectOptionAccessible(nsIDOMNode *aNode,
-                                                    nsIAccessible *aAccParent,
-                                                    nsIWeakReference *aPresShell,
-                                                    nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLTableAccessible(nsIFrame *aFrame,
-                                             nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLTableCellAccessible(nsIFrame *aFrame,
-                                                 nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLTextAccessible(nsIFrame *aFrame,
-                                            nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLTextFieldAccessible(nsIFrame *aFrame,
-                                                 nsIAccessible **aAccessible);
-  virtual nsresult CreateHTMLCaptionAccessible(nsIFrame *aFrame,
-                                               nsIAccessible **aAccessible);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLBRAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTML4ButtonAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLButtonAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLCaptionAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLCheckboxAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLComboboxAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLGroupboxAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLHRAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLImageAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLLabelAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLLIAccessible(nsIContent* aContent, nsIPresShell* aPresShell,
+                           const nsAString& aBulletText);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLListboxAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLMediaAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLObjectFrameAccessible(nsObjectFrame* aFrame, nsIContent* aContent,
+                                    nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLRadioButtonAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLTableAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLTableCellAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLTextAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHTMLTextFieldAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateHyperTextAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
+  virtual already_AddRefed<nsAccessible>
+    CreateOuterDocAccessible(nsIContent* aContent, nsIPresShell* aPresShell);
 
-  virtual nsresult AddNativeRootAccessible(void *aAtkAccessible,
-                                           nsIAccessible **aAccessible);
-  virtual nsresult RemoveNativeRootAccessible(nsIAccessible *aRootAccessible);
+  virtual nsAccessible* AddNativeRootAccessible(void* aAtkAccessible);
+  virtual void RemoveNativeRootAccessible(nsAccessible* aRootAccessible);
 
   virtual nsresult InvalidateSubtreeFor(nsIPresShell *aPresShell,
                                         nsIContent *aContent,
                                         PRUint32 aChangeType);
 
   virtual void NotifyOfAnchorJumpTo(nsIContent *aTarget);
 
   virtual void PresShellDestroyed(nsIPresShell* aPresShell);
@@ -236,61 +227,48 @@ private:
   PRBool Init();
 
   /**
    * Shutdowns accessibility service.
    */
   void Shutdown();
 
   /**
-   * Return presentation shell, DOM node for the given frame.
-   *
-   * @param aFrame    [in] the given frame
-   * @param aShell    [out] presentation shell for DOM node associated with the
-   *                    given frame
-   * @param aContent  [out] DOM node associated with the given frame
-   */
-  nsresult GetInfo(nsIFrame *aFrame, nsIWeakReference **aShell,
-                   nsIContent **aContent);
-
-  /**
    * Return accessible for HTML area element associated with an image map.
    */
-  already_AddRefed<nsAccessible>
-    GetAreaAccessible(nsIFrame *aImageFrame, nsINode *aAreaNode,
-                      nsIWeakReference *aWeakShell);
+  nsAccessible* GetAreaAccessible(nsIFrame* aImageFrame, nsINode* aAreaNode,
+                                  nsIWeakReference* aWeakShell);
 
   /**
    * Create accessible for the element implementing nsIAccessibleProvider
    * interface.
    */
   already_AddRefed<nsAccessible>
-    CreateAccessibleByType(nsIContent *aContent, nsIWeakReference *aWeakShell);
+    CreateAccessibleByType(nsIContent* aContent, nsIWeakReference* aWeakShell);
 
   /**
    * Create accessible for HTML node by tag name.
    */
   already_AddRefed<nsAccessible>
-    CreateHTMLAccessibleByMarkup(nsIFrame *aFrame, nsIWeakReference *aWeakShell,
-                                 nsINode *aNode);
+    CreateHTMLAccessibleByMarkup(nsIFrame* aFrame, nsIContent* aContent,
+                                 nsIWeakReference* aWeakShell);
 
   /**
    * Create accessible if parent is a deck frame.
    */
   already_AddRefed<nsAccessible>
-    CreateAccessibleForDeckChild(nsIFrame *aFrame, nsIContent *aContent,
-                                 nsIWeakReference *aWeakShell);
+    CreateAccessibleForDeckChild(nsIFrame* aFrame, nsIContent* aContent,
+                                 nsIWeakReference* aWeakShell);
 
 #ifdef MOZ_XUL
   /**
    * Create accessible for XUL tree element.
    */
   already_AddRefed<nsAccessible>
-    CreateAccessibleForXULTree(nsIContent *aContent,
-                               nsIWeakReference *aWeakShell);
+    CreateAccessibleForXULTree(nsIContent* aContent, nsIWeakReference* aWeakShell);
 #endif
 
   /**
    * Reference for accessibility service.
    */
   static nsAccessibilityService *gAccessibilityService;
 
   /**
@@ -324,17 +302,17 @@ GetAccService()
 /**
  * Map nsIAccessibleRole constants to strings. Used by
  * nsIAccessibleRetrieval::getStringRole() method.
  */
 static const char kRoleNames[][20] = {
   "nothing",             //ROLE_NOTHING
   "titlebar",            //ROLE_TITLEBAR
   "menubar",             //ROLE_MENUBAR
-  "scrollbar",           //ROLE_SCROLLBAR 
+  "scrollbar",           //ROLE_SCROLLBAR
   "grip",                //ROLE_GRIP
   "sound",               //ROLE_SOUND
   "cursor",              //ROLE_CURSOR
   "caret",               //ROLE_CARET
   "alert",               //ROLE_ALERT
   "window",              //ROLE_WINDOW
   "internal frame",      //ROLE_INTERNAL_FRAME
   "menupopup",           //ROLE_MENUPOPUP
@@ -441,17 +419,17 @@ static const char kRoleNames[][20] = {
   "parent menuitem",     //ROLE_PARENT_MENUITEM
   "calendar",            //ROLE_CALENDAR
   "combobox list",       //ROLE_COMBOBOX_LIST
   "combobox option",     //ROLE_COMBOBOX_OPTION
   "image map",           //ROLE_IMAGE_MAP
   "listbox option",      //ROLE_OPTION
   "listbox rich option", //ROLE_RICH_OPTION
   "listbox",             //ROLE_LISTBOX
-  "flat equation",       //ROLE_FLAT_EQUATION  
+  "flat equation",       //ROLE_FLAT_EQUATION
   "gridcell",            //ROLE_GRID_CELL
   "embedded object"      //ROLE_EMBEDDED_OBJECT
 };
 
 /**
  * Map nsIAccessibleEvents constants to strings. Used by
  * nsIAccessibleRetrieval::getStringEventType() method.
  */
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -3003,17 +3003,17 @@ PRBool nsAccessible::CheckVisibilityInPa
       }
       view = view->GetParent();
     }
 
     nsIDocument* parentDoc = document->GetParentDocument();
     if (parentDoc != nsnull) {
       nsIContent* content = parentDoc->FindContentForSubDocument(document);
       if (content != nsnull) {
-        nsIPresShell* shell = parentDoc->GetPrimaryShell();
+        nsIPresShell* shell = parentDoc->GetShell();
         if (!shell) {
           return PR_FALSE;
         }
         nsIFrame* frame = content->GetPrimaryFrame();
         while (frame != nsnull && !frame->HasView()) {
           frame = frame->GetParent();
         }
 
--- a/accessible/src/base/nsApplicationAccessible.cpp
+++ b/accessible/src/base/nsApplicationAccessible.cpp
@@ -409,32 +409,32 @@ nsAccessible*
 nsApplicationAccessible::GetParent()
 {
   return nsnull;
 }
 
 void
 nsApplicationAccessible::InvalidateChildren()
 {
-  // Do nothing because application children are kept updated by
-  // AddRootAccessible() and RemoveRootAccessible() method calls.
+  // Do nothing because application children are kept updated by AppendChild()
+  // and RemoveChild() method calls.
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessible protected methods
 
 void
 nsApplicationAccessible::CacheChildren()
 {
   // CacheChildren is called only once for application accessible when its
   // children are requested because empty InvalidateChldren() prevents its
   // repeated calls.
 
-  // Basically children are kept updated by Add/RemoveRootAccessible method
-  // calls. However if there are open windows before accessibility was started
+  // Basically children are kept updated by Append/RemoveChild method calls.
+  // However if there are open windows before accessibility was started
   // then we need to make sure root accessibles for open windows are created so
   // that all root accessibles are stored in application accessible children
   // array.
 
   nsCOMPtr<nsIWindowMediator> windowMediator =
     do_GetService(NS_WINDOWMEDIATOR_CONTRACTID);
 
   nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
@@ -448,19 +448,18 @@ nsApplicationAccessible::CacheChildren()
   while (hasMore) {
     nsCOMPtr<nsISupports> window;
     windowEnumerator->GetNext(getter_AddRefs(window));
     nsCOMPtr<nsIDOMWindow> DOMWindow = do_QueryInterface(window);
     if (DOMWindow) {
       nsCOMPtr<nsIDOMDocument> DOMDocument;
       DOMWindow->GetDocument(getter_AddRefs(DOMDocument));
       if (DOMDocument) {
-        nsCOMPtr<nsIAccessible> accessible;
-        GetAccService()->GetAccessibleFor(DOMDocument,
-                                          getter_AddRefs(accessible));
+        nsCOMPtr<nsIDocument> docNode(do_QueryInterface(DOMDocument));
+        GetAccService()->GetDocAccessible(docNode); // ensure creation
       }
     }
     windowEnumerator->HasMoreElements(&hasMore);
   }
 }
 
 nsAccessible*
 nsApplicationAccessible::GetSiblingAtOffset(PRInt32 aOffset, nsresult* aError)
@@ -476,40 +475,32 @@ nsApplicationAccessible::GetSiblingAtOff
     *aError = NS_OK; // fail peacefully
 
   return nsnull;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // Public methods
 
-nsresult
-nsApplicationAccessible::AddRootAccessible(nsIAccessible *aRootAccessible)
+PRBool
+nsApplicationAccessible::AppendChild(nsAccessible* aChild)
 {
-  NS_ENSURE_ARG_POINTER(aRootAccessible);
-
-  nsRefPtr<nsAccessible> rootAcc = do_QueryObject(aRootAccessible);
+  if (!mChildren.AppendElement(aChild))
+    return PR_FALSE;
 
-  if (!mChildren.AppendElement(rootAcc))
-    return NS_ERROR_FAILURE;
-
-  rootAcc->SetParent(this);
-
-  return NS_OK;
+  aChild->SetParent(this);
+  return PR_TRUE;
 }
 
-nsresult
-nsApplicationAccessible::RemoveRootAccessible(nsIAccessible *aRootAccessible)
+PRBool
+nsApplicationAccessible::RemoveChild(nsAccessible* aChild)
 {
-  NS_ENSURE_ARG_POINTER(aRootAccessible);
-
-  // It's not needed to void root accessible parent because this method is
-  // called on root accessible shutdown and its parent will be cleared
-  // properly.
-  return mChildren.RemoveElement(aRootAccessible) ? NS_OK : NS_ERROR_FAILURE;
+  // It's not needed to unbind root accessible from parent because this method
+  // is called when root accessible is shutdown and it'll be unbound properly.
+  return mChildren.RemoveElement(aChild);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsIAccessNode
 
 NS_IMETHODIMP
 nsApplicationAccessible::GetDOMNode(nsIDOMNode **aDOMNode)
 {
--- a/accessible/src/base/nsApplicationAccessible.h
+++ b/accessible/src/base/nsApplicationAccessible.h
@@ -111,20 +111,18 @@ public:
 
   // nsAccessible
   virtual nsresult GetARIAState(PRUint32 *aState, PRUint32 *aExtraState);
   virtual nsresult GetRoleInternal(PRUint32 *aRole);
   virtual nsresult GetStateInternal(PRUint32 *aState, PRUint32 *aExtraState);
   virtual nsAccessible* GetParent();
 
   virtual void InvalidateChildren();
-
-  // nsApplicationAccessible
-  virtual nsresult AddRootAccessible(nsIAccessible *aRootAccWrap);
-  virtual nsresult RemoveRootAccessible(nsIAccessible *aRootAccWrap);
+  virtual PRBool AppendChild(nsAccessible* aChild);
+  virtual PRBool RemoveChild(nsAccessible* aChild);
 
 protected:
 
   // nsAccessible
   virtual void CacheChildren();
   virtual nsAccessible* GetSiblingAtOffset(PRInt32 aOffset,
                                            nsresult *aError = nsnull);
 
--- a/accessible/src/base/nsCaretAccessible.cpp
+++ b/accessible/src/base/nsCaretAccessible.cpp
@@ -356,17 +356,17 @@ nsCaretAccessible::GetSelectionControlle
 {
   if (!aContent)
     return nsnull;
 
   nsIDocument *document = aContent->GetOwnerDoc();
   if (!document)
     return nsnull;
 
-  nsIPresShell *presShell = document->GetPrimaryShell();
+  nsIPresShell *presShell = document->GetShell();
   if (!presShell)
     return nsnull;
 
   nsIFrame *frame = aContent->GetPrimaryFrame();
   if (!frame)
     return nsnull;
 
   nsPresContext *presContext = presShell->GetPresContext();
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -102,17 +102,17 @@ nsCoreUtils::DispatchClickEvent(nsITreeB
     return;
 
   nsCOMPtr<nsIContent> tcContent(do_QueryInterface(tcElm));
   nsIDocument *document = tcContent->GetCurrentDoc();
   if (!document)
     return;
 
   nsIPresShell *presShell = nsnull;
-  presShell = document->GetPrimaryShell();
+  presShell = document->GetShell();
   if (!presShell)
     return;
 
   // Ensure row is visible.
   aTreeBoxObj->EnsureRowIsVisible(aRowIndex);
 
   // Calculate x and y coordinates.
   PRInt32 x = 0, y = 0, width = 0, height = 0;
@@ -214,17 +214,17 @@ nsCoreUtils::GetAccessKeyFor(nsIContent 
   // nsIEventStateManager::GetRegisteredAccessKey() method.
   if (!aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::accesskey))
     return 0;
 
   nsCOMPtr<nsIDocument> doc = aContent->GetOwnerDoc();
   if (!doc)
     return 0;
 
-  nsCOMPtr<nsIPresShell> presShell = doc->GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> presShell = doc->GetShell();
   if (!presShell)
     return 0;
 
   nsPresContext *presContext = presShell->GetPresContext();
   if (!presContext)
     return 0;
 
   nsIEventStateManager *esm = presContext->EventStateManager();
--- a/accessible/src/base/nsCoreUtils.h
+++ b/accessible/src/base/nsCoreUtils.h
@@ -251,17 +251,17 @@ public:
   static PRBool IsCorrectFrameType(nsIFrame* aFrame, nsIAtom* aAtom);
 
   /**
    * Return presShell for the document containing the given DOM node.
    */
   static nsIPresShell *GetPresShellFor(nsINode *aNode)
   {
     nsIDocument *document = aNode->GetOwnerDoc();
-    return document ? document->GetPrimaryShell() : nsnull;
+    return document ? document->GetShell() : nsnull;
   }
   static already_AddRefed<nsIWeakReference> GetWeakShellFor(nsINode *aNode)
   {
     nsCOMPtr<nsIWeakReference> weakShell =
       do_GetWeakReference(GetPresShellFor(aNode));
     return weakShell.forget();
   }
 
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -668,17 +668,17 @@ nsDocAccessible::IsDefunct()
 void nsDocAccessible::GetBoundsRect(nsRect& aBounds, nsIFrame** aRelativeFrame)
 {
   *aRelativeFrame = GetFrame();
 
   nsIDocument *document = mDocument;
   nsIDocument *parentDoc = nsnull;
 
   while (document) {
-    nsIPresShell *presShell = document->GetPrimaryShell();
+    nsIPresShell *presShell = document->GetShell();
     if (!presShell) {
       return;
     }
 
     nsRect scrollPort;
     nsIScrollableFrame* sf = presShell->GetRootScrollFrameAsScrollableExternal();
     if (sf) {
       scrollPort = sf->GetScrollPortRect();
--- a/accessible/src/base/nsEventShell.cpp
+++ b/accessible/src/base/nsEventShell.cpp
@@ -190,37 +190,32 @@ nsAccEventQueue::PrepareFlush()
 void
 nsAccEventQueue::WillRefresh(mozilla::TimeStamp aTime)
 {
   // If the document accessible is now shut down, don't fire events in it
   // anymore.
   if (!mDocument)
     return;
 
-  nsCOMPtr<nsIPresShell> presShell = mDocument->GetPresShell();
-  if (!presShell)
-    return;
-
   // Process only currently queued events. Newly appended events during events
   // flushing won't be processed.
   nsTArray < nsRefPtr<nsAccEvent> > events;
   events.SwapElements(mEvents);
   PRUint32 length = events.Length();
   NS_ASSERTION(length, "How did we get here without events to fire?");
 
   for (PRUint32 index = 0; index < length; index ++) {
 
-    // No presshell means the document was shut down during event handling
-    // by AT.
-    if (!mDocument || !mDocument->HasWeakShell())
-      break;
-
     nsAccEvent *accEvent = events[index];
     if (accEvent->mEventRule != nsAccEvent::eDoNotEmit)
       mDocument->ProcessPendingEvent(accEvent);
+
+    // No document means it was shut down during event handling by AT
+    if (!mDocument)
+      return;
   }
 
   if (mEvents.Length() == 0) {
     nsCOMPtr<nsIPresShell> shell = mDocument->GetPresShell();
     if (!shell ||
         shell->RemoveRefreshObserver(this, Flush_Display)) {
       mObservingRefresh = PR_FALSE;
     }
--- a/accessible/src/base/nsRelUtils.cpp
+++ b/accessible/src/base/nsRelUtils.cpp
@@ -86,20 +86,17 @@ nsRelUtils::AddTarget(PRUint32 aRelation
 nsresult
 nsRelUtils::AddTargetFromContent(PRUint32 aRelationType,
                                  nsIAccessibleRelation **aRelation,
                                  nsIContent *aContent)
 {
   if (!aContent)
     return NS_OK_NO_RELATION_TARGET;
 
-  nsCOMPtr<nsIDOMNode> node(do_QueryInterface(aContent));
-
-  nsCOMPtr<nsIAccessible> accessible;
-  GetAccService()->GetAccessibleFor(node, getter_AddRefs(accessible));
+  nsAccessible* accessible = GetAccService()->GetAccessible(aContent);
   return AddTarget(aRelationType, aRelation, accessible);
 }
 
 nsresult
 nsRelUtils::AddTargetFromIDRefAttr(PRUint32 aRelationType,
                                    nsIAccessibleRelation **aRelation,
                                    nsIContent *aContent, nsIAtom *aAttr,
                                    PRBool aMayBeAnon)
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -826,36 +826,34 @@ void nsRootAccessible::GetTargetNode(nsI
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessNode
 
 PRBool
 nsRootAccessible::Init()
 {
   nsApplicationAccessible *applicationAcc = GetApplicationAccessible();
-  if (!applicationAcc)
+  if (!applicationAcc || !applicationAcc->AppendChild(this))
     return PR_FALSE;
 
-  applicationAcc->AddRootAccessible(this);
-
   return nsDocAccessibleWrap::Init();
 }
 
 void
 nsRootAccessible::Shutdown()
 {
   // Called manually or by nsAccessNode::LastRelease()
   if (!mWeakShell)
     return;  // Already shutdown
 
   nsApplicationAccessible *applicationAcc = GetApplicationAccessible();
   if (!applicationAcc)
     return;
 
-  applicationAcc->RemoveRootAccessible(this);
+  applicationAcc->RemoveChild(this);
 
   mCurrentARIAMenubar = nsnull;
 
   nsDocAccessibleWrap::Shutdown();
 }
 
 // nsRootAccessible protected member
 already_AddRefed<nsIDocShellTreeItem>
@@ -935,18 +933,18 @@ nsRootAccessible::GetRelationByType(PRUi
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessible
 
 nsAccessible*
 nsRootAccessible::GetParent()
 {
-  // Parent has been setted in nsApplicationAccesible::AddRootAccessible()
-  // when root accessible was intialized.
+  // Parent has been set in nsApplicationAccesible::AppendChild() when root
+  // accessible was initialized.
   return mParent;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // Protected members
 
 nsresult
 nsRootAccessible::HandlePopupShownEvent(nsAccessible *aAccessible)
--- a/accessible/src/html/nsHTMLSelectAccessible.cpp
+++ b/accessible/src/html/nsHTMLSelectAccessible.cpp
@@ -817,20 +817,18 @@ nsIContent* nsHTMLSelectOptionAccessible
   if (aExtraState)
     *aExtraState = 0;
 
   nsIContent *content = mContent;
   while (content && content->Tag() != nsAccessibilityAtoms::select) {
     content = content->GetParent();
   }
 
-  nsCOMPtr<nsIDOMNode> selectNode(do_QueryInterface(content));
-  if (selectNode) {
-    nsCOMPtr<nsIAccessible> selAcc;
-    GetAccService()->GetAccessibleFor(selectNode, getter_AddRefs(selAcc));
+  if (content) {
+    nsAccessible* selAcc = GetAccService()->GetAccessible(content);
     if (selAcc) {
       selAcc->GetState(aState, aExtraState);
       return content;
     }
   }
   return nsnull; 
 }
 
--- a/accessible/src/msaa/CAccessibleAction.cpp
+++ b/accessible/src/msaa/CAccessibleAction.cpp
@@ -67,17 +67,17 @@ CAccessibleAction::QueryInterface(REFIID
 // IAccessibleAction
 
 STDMETHODIMP
 CAccessibleAction::nActions(long *aNumActions)
 {
 __try {
   *aNumActions = 0;
 
-  nsCOMPtr<nsIAccessible> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessible> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   PRUint8 count = 0;
   nsresult rv = acc->GetNumActions(&count);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
@@ -87,17 +87,17 @@ CAccessibleAction::nActions(long *aNumAc
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return E_FAIL;
 }
 
 STDMETHODIMP
 CAccessibleAction::doAction(long aActionIndex)
 {
 __try {
-  nsCOMPtr<nsIAccessible> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessible> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   PRUint8 index = static_cast<PRUint8>(aActionIndex);
   nsresult rv = acc->DoAction(index);
   return GetHRESULT(rv);
 
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
@@ -105,17 +105,17 @@ CAccessibleAction::doAction(long aAction
 }
 
 STDMETHODIMP
 CAccessibleAction::get_description(long aActionIndex, BSTR *aDescription)
 {
 __try {
   *aDescription = NULL;
 
-  nsCOMPtr<nsIAccessible> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessible> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   nsAutoString description;
   PRUint8 index = static_cast<PRUint8>(aActionIndex);
   nsresult rv = acc->GetActionDescription(index, description);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -135,17 +135,17 @@ STDMETHODIMP
 CAccessibleAction::get_keyBinding(long aActionIndex, long aNumMaxBinding,
                                   BSTR **aKeyBinding,
                                   long *aNumBinding)
 {
 __try {
   *aKeyBinding = NULL;
   *aNumBinding = 0;
 
-  nsCOMPtr<nsIAccessible> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessible> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   nsCOMPtr<nsIDOMDOMStringList> keys;
   PRUint8 index = static_cast<PRUint8>(aActionIndex);
   nsresult rv = acc->GetKeyBindings(index, getter_AddRefs(keys));
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -192,17 +192,17 @@ CAccessibleAction::get_keyBinding(long a
 }
 
 STDMETHODIMP
 CAccessibleAction::get_name(long aActionIndex, BSTR *aName)
 {
 __try {
   *aName = NULL;
 
-  nsCOMPtr<nsIAccessible> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessible> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   nsAutoString name;
   PRUint8 index = static_cast<PRUint8>(aActionIndex);
   nsresult rv = acc->GetActionName(index, name);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
--- a/accessible/src/msaa/CAccessibleAction.h
+++ b/accessible/src/msaa/CAccessibleAction.h
@@ -40,18 +40,17 @@
 
 #ifndef _ACCESSIBLE_ACTION_H
 #define _ACCESSIBLE_ACTION_H
 
 #include "nsISupports.h"
 
 #include "AccessibleAction.h"
 
-class CAccessibleAction: public nsISupports,
-                         public IAccessibleAction
+class CAccessibleAction: public IAccessibleAction
 {
 public:
 
   // IUnknown
   STDMETHODIMP QueryInterface(REFIID, void**);
 
   // IAccessibleAction
   virtual HRESULT STDMETHODCALLTYPE nActions(
@@ -73,16 +72,19 @@ public:
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_name(
       /* [in] */ long actionIndex,
       /* [retval][out] */ BSTR *name);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_localizedName(
       /* [in] */ long actionIndex,
       /* [retval][out] */ BSTR *localizedName);
 
+  // nsISupports
+  NS_IMETHOD QueryInterface(const nsIID& uuid, void** result) = 0;
+
 };
 
 
 #define FORWARD_IACCESSIBLEACTION(Class)                                       \
 virtual HRESULT STDMETHODCALLTYPE nActions(long *nActions)                     \
 {                                                                              \
   return Class::nActions(nActions);                                            \
 }                                                                              \
--- a/accessible/src/msaa/CAccessibleComponent.cpp
+++ b/accessible/src/msaa/CAccessibleComponent.cpp
@@ -80,17 +80,17 @@ CAccessibleComponent::QueryInterface(REF
 
 STDMETHODIMP
 CAccessibleComponent::get_locationInParent(long *aX, long *aY)
 {
 __try {
   *aX = 0;
   *aY = 0;
 
-  nsCOMPtr<nsIAccessible> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessible> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   // If the object is not on any screen the returned position is (0,0).
   PRUint32 states = 0;
   nsresult rv = acc->GetState(&states, nsnull);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -155,17 +155,17 @@ CAccessibleComponent::get_background(IA2
 
 HRESULT
 CAccessibleComponent::GetARGBValueFromCSSProperty(const nsAString& aPropName,
                                                   IA2Color *aColorValue)
 {
 __try {
   *aColorValue = 0;
 
-  nsCOMPtr<nsIAccessNode> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessNode> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   nsCOMPtr<nsIDOMCSSPrimitiveValue> cssValue;
   nsresult rv = acc->GetComputedStyleCSSValue(EmptyString(), aPropName,
                                               getter_AddRefs(cssValue));
   if (NS_FAILED(rv) || !cssValue)
     return GetHRESULT(rv);
--- a/accessible/src/msaa/CAccessibleComponent.h
+++ b/accessible/src/msaa/CAccessibleComponent.h
@@ -40,18 +40,17 @@
 
 #ifndef _ACCESSIBLE_COMPONENt_H
 #define _ACCESSIBLE_COMPONENT_H
 
 #include "nsISupports.h"
 
 #include "AccessibleComponent.h"
 
-class CAccessibleComponent: public nsISupports,
-                            public IAccessibleComponent
+class CAccessibleComponent: public IAccessibleComponent
 {
 public:
 
   // IUnknown
   STDMETHODIMP QueryInterface(REFIID, void**);
 
   // IAccessibleComponent
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_locationInParent(
@@ -59,16 +58,19 @@ public:
       /* [retval][out] */ long *y);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_foreground(
       /* [retval][out] */ IA2Color *foreground);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_background(
       /* [retval][out] */ IA2Color *background);
 
+  // nsISupports
+  NS_IMETHOD QueryInterface(const nsIID& uuid, void** result) = 0;
+
 protected:
 
   /**
    * Return ARGB value for CSS property like 'color' or 'background-color'.
    */
   HRESULT GetARGBValueFromCSSProperty(const nsAString& aPropName,
                                       IA2Color *aColorValue);
 };
--- a/accessible/src/msaa/CAccessibleEditableText.cpp
+++ b/accessible/src/msaa/CAccessibleEditableText.cpp
@@ -43,31 +43,31 @@
 #include "nsIAccessibleEditableText.h"
 #include "AccessibleEditableText_i.c"
 #include "nsAccessNodeWrap.h"
 
 #include "nsCOMPtr.h"
 #include "nsString.h"
 
 #define GET_NSIACCESSIBLEEDITABLETEXT \
-nsCOMPtr<nsIAccessibleEditableText> textAcc(do_QueryInterface(this));\
+nsCOMPtr<nsIAccessibleEditableText> textAcc(do_QueryObject(this));\
 NS_ASSERTION(textAcc,\
              "Subclass of CAccessibleEditableText doesn't implement nsIAccessibleEditableText");\
 if (!textAcc)\
   return E_FAIL;\
 
 // IUnknown
 
 STDMETHODIMP
 CAccessibleEditableText::QueryInterface(REFIID iid, void** ppv)
 {
   *ppv = NULL;
 
   if (IID_IAccessibleEditableText == iid) {
-    nsCOMPtr<nsIAccessibleEditableText> editTextAcc(do_QueryInterface(this));
+    nsCOMPtr<nsIAccessibleEditableText> editTextAcc(do_QueryObject(this));
     if (!editTextAcc)
       return E_NOINTERFACE;
     *ppv = static_cast<IAccessibleEditableText*>(this);
     (reinterpret_cast<IUnknown*>(*ppv))->AddRef(); 
     return S_OK;
   }
 
   return E_NOINTERFACE;
--- a/accessible/src/msaa/CAccessibleEditableText.h
+++ b/accessible/src/msaa/CAccessibleEditableText.h
@@ -41,18 +41,17 @@
 #ifndef _ACCESSIBLE_EDITABLETEXT_H
 #define _ACCESSIBLE_EDITABLETEXT_H
 
 #include "nsISupports.h"
 #include "nsIAccessibleEditableText.h"
 
 #include "AccessibleEditableText.h"
 
-class CAccessibleEditableText: public nsISupports,
-                               public IAccessibleEditableText
+class CAccessibleEditableText: public IAccessibleEditableText
 {
 public:
 
   // IUnknown
   STDMETHODIMP QueryInterface(REFIID, void**);
 
   // IAccessibleEditableText
   virtual HRESULT STDMETHODCALLTYPE copyText(
@@ -78,12 +77,15 @@ public:
       /* [in] */ long startOffset,
       /* [in] */ long endOffset,
       /* [in] */ BSTR *text);
 
   virtual HRESULT STDMETHODCALLTYPE setAttributes(
       /* [in] */ long startOffset,
       /* [in] */ long endOffset,
       /* [in] */ BSTR *attributes);
+
+  // nsISupports
+  NS_IMETHOD QueryInterface(const nsIID& uuid, void** result) = 0;
 };
 
 #endif
 
--- a/accessible/src/msaa/CAccessibleHyperlink.cpp
+++ b/accessible/src/msaa/CAccessibleHyperlink.cpp
@@ -57,17 +57,17 @@
 // IUnknown
 
 STDMETHODIMP
 CAccessibleHyperlink::QueryInterface(REFIID iid, void** ppv)
 {
   *ppv = NULL;
 
   if (IID_IAccessibleHyperlink == iid) {
-    nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryInterface(this));
+    nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryObject(this));
     if (!acc)
       return E_NOINTERFACE;
 
     *ppv = static_cast<IAccessibleHyperlink*>(this);
     (reinterpret_cast<IUnknown*>(*ppv))->AddRef();
     return S_OK;
   }
 
@@ -77,17 +77,17 @@ CAccessibleHyperlink::QueryInterface(REF
 // IAccessibleHyperlink
 
 STDMETHODIMP
 CAccessibleHyperlink::get_anchor(long aIndex, VARIANT *aAnchor)
 {
 __try {
   VariantInit(aAnchor);
 
-  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   nsCOMPtr<nsIAccessible> anchor;
   nsresult rv = acc->GetAnchor(aIndex, getter_AddRefs(anchor));
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
@@ -110,17 +110,17 @@ CAccessibleHyperlink::get_anchor(long aI
 }
 
 STDMETHODIMP
 CAccessibleHyperlink::get_anchorTarget(long aIndex, VARIANT *aAnchorTarget)
 {
 __try {
   VariantInit(aAnchorTarget);
 
-  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   nsCOMPtr<nsIURI> uri;
   nsresult rv = acc->GetURI(aIndex, getter_AddRefs(uri));
   if (NS_FAILED(rv) || !uri)
     return GetHRESULT(rv);
 
@@ -148,17 +148,17 @@ CAccessibleHyperlink::get_anchorTarget(l
 }
 
 STDMETHODIMP
 CAccessibleHyperlink::get_startIndex(long *aIndex)
 {
 __try {
   *aIndex = 0;
 
-  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   PRInt32 index = 0;
   nsresult rv = acc->GetStartIndex(&index);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
@@ -170,17 +170,17 @@ CAccessibleHyperlink::get_startIndex(lon
 }
 
 STDMETHODIMP
 CAccessibleHyperlink::get_endIndex(long *aIndex)
 {
 __try {
   *aIndex = 0;
 
-  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   PRInt32 index = 0;
   nsresult rv = acc->GetEndIndex(&index);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
@@ -192,17 +192,17 @@ CAccessibleHyperlink::get_endIndex(long 
 }
 
 STDMETHODIMP
 CAccessibleHyperlink::get_valid(boolean *aValid)
 {
 __try {
   *aValid = false;
 
-  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   PRBool isValid = PR_FALSE;
   nsresult rv = acc->GetValid(&isValid);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
--- a/accessible/src/msaa/CAccessibleHyperlink.h
+++ b/accessible/src/msaa/CAccessibleHyperlink.h
@@ -69,12 +69,15 @@ public:
       /* [retval][out] */ long *index);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_endIndex(
       /* [retval][out] */ long *index);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_valid(
       /* [retval][out] */ boolean *valid);
 
+  // nsISupports
+  NS_IMETHOD QueryInterface(const nsIID& uuid, void** result) = 0;
+
 };
 
 #endif
 
--- a/accessible/src/msaa/CAccessibleHypertext.cpp
+++ b/accessible/src/msaa/CAccessibleHypertext.cpp
@@ -46,17 +46,17 @@
 
 // IUnknown
 
 STDMETHODIMP
 CAccessibleHypertext::QueryInterface(REFIID iid, void** ppv)
 {
   *ppv = NULL;
   if (IID_IAccessibleHypertext == iid) {
-    nsCOMPtr<nsIAccessibleHyperText> hyperAcc(do_QueryInterface(this));
+    nsCOMPtr<nsIAccessibleHyperText> hyperAcc(do_QueryObject(this));
     if (!hyperAcc)
       return E_NOINTERFACE;
 
     *ppv = static_cast<IAccessibleHypertext*>(this);
     (reinterpret_cast<IUnknown*>(*ppv))->AddRef();
     return S_OK;
   }
 
@@ -112,17 +112,17 @@ CAccessibleHypertext::get_hyperlink(long
 }
 
 STDMETHODIMP
 CAccessibleHypertext::get_hyperlinkIndex(long aCharIndex, long *aHyperlinkIndex)
 {
 __try {
   *aHyperlinkIndex = 0;
 
-  nsCOMPtr<nsIAccessibleHyperText> hyperAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleHyperText> hyperAcc(do_QueryObject(this));
   if (!hyperAcc)
     return E_FAIL;
 
   PRInt32 index = 0;
   nsresult rv = hyperAcc->GetLinkIndexAtOffset(aCharIndex, &index);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
--- a/accessible/src/msaa/CAccessibleImage.cpp
+++ b/accessible/src/msaa/CAccessibleImage.cpp
@@ -53,17 +53,17 @@
 // IUnknown
 
 STDMETHODIMP
 CAccessibleImage::QueryInterface(REFIID iid, void** ppv)
 {
   *ppv = NULL;
 
   if (IID_IAccessibleImage == iid) {
-    nsCOMPtr<nsIAccessibleImage> imageAcc(do_QueryInterface(this));
+    nsCOMPtr<nsIAccessibleImage> imageAcc(do_QueryObject(this));
     if (!imageAcc)
       return E_FAIL;
 
     *ppv = static_cast<IAccessibleImage*>(this);
     (reinterpret_cast<IUnknown*>(*ppv))->AddRef();
     return S_OK;
   }
 
@@ -73,17 +73,17 @@ CAccessibleImage::QueryInterface(REFIID 
 // IAccessibleImage
 
 STDMETHODIMP
 CAccessibleImage::get_description(BSTR *aDescription)
 {
 __try {
   *aDescription = NULL;
 
-  nsCOMPtr<nsIAccessible> acc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessible> acc(do_QueryObject(this));
   if (!acc)
     return E_FAIL;
 
   nsAutoString description;
   nsresult rv = acc->GetName(description);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
@@ -105,17 +105,17 @@ CAccessibleImage::get_imagePosition(enum
 __try {
   *aX = 0;
   *aY = 0;
 
   PRUint32 geckoCoordType = (aCoordType == IA2_COORDTYPE_SCREEN_RELATIVE) ?
     nsIAccessibleCoordinateType::COORDTYPE_SCREEN_RELATIVE :
     nsIAccessibleCoordinateType::COORDTYPE_PARENT_RELATIVE;
 
-  nsCOMPtr<nsIAccessibleImage> imageAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleImage> imageAcc(do_QueryObject(this));
   if (!imageAcc)
     return E_FAIL;
 
   PRInt32 x = 0, y = 0;
   nsresult rv = imageAcc->GetImagePosition(geckoCoordType, &x, &y);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
@@ -130,17 +130,17 @@ CAccessibleImage::get_imagePosition(enum
 
 STDMETHODIMP
 CAccessibleImage::get_imageSize(long *aHeight, long *aWidth)
 {
 __try {
   *aHeight = 0;
   *aWidth = 0;
 
-  nsCOMPtr<nsIAccessibleImage> imageAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleImage> imageAcc(do_QueryObject(this));
   if (!imageAcc)
     return E_FAIL;
 
   PRInt32 x = 0, y = 0, width = 0, height = 0;
   nsresult rv = imageAcc->GetImageSize(&width, &height);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
--- a/accessible/src/msaa/CAccessibleImage.h
+++ b/accessible/src/msaa/CAccessibleImage.h
@@ -40,18 +40,17 @@
 
 #ifndef _ACCESSIBLE_IMAGE_H
 #define _ACCESSIBLE_IMAGE_H
 
 #include "nsISupports.h"
 
 #include "AccessibleImage.h"
 
-class CAccessibleImage: public nsISupports,
-                        public IAccessibleImage
+class CAccessibleImage: public IAccessibleImage
 {
 public:
 
   // IUnknown
   STDMETHODIMP QueryInterface(REFIID, void**);
 
   // IAccessibleImage
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_description(
@@ -61,12 +60,15 @@ public:
       /* [in] */ enum IA2CoordinateType coordinateType,
       /* [out] */ long *x,
       /* [retval][out] */ long *y);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_imageSize(
       /* [out] */ long *height,
       /* [retval][out] */ long *width);
 
+  // nsISupports
+  NS_IMETHOD QueryInterface(const nsIID& uuid, void** result) = 0;
+
 };
 
 #endif
 
--- a/accessible/src/msaa/CAccessibleTable.cpp
+++ b/accessible/src/msaa/CAccessibleTable.cpp
@@ -83,17 +83,17 @@ CAccessibleTable::QueryInterface(REFIID 
 
 STDMETHODIMP
 CAccessibleTable::get_accessibleAt(long aRow, long aColumn,
                                    IUnknown **aAccessible)
 {
 __try {
   *aAccessible = NULL;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   nsCOMPtr<nsIAccessible> cell;
   nsresult rv = tableAcc->GetCellAt(aRow, aColumn, getter_AddRefs(cell));
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -115,17 +115,17 @@ CAccessibleTable::get_accessibleAt(long 
 }
 
 STDMETHODIMP
 CAccessibleTable::get_caption(IUnknown **aAccessible)
 {
 __try {
   *aAccessible = NULL;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   nsCOMPtr<nsIAccessible> caption;
   nsresult rv = tableAcc->GetCaption(getter_AddRefs(caption));
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -151,17 +151,17 @@ CAccessibleTable::get_caption(IUnknown *
 
 STDMETHODIMP
 CAccessibleTable::get_childIndex(long aRowIndex, long aColumnIndex,
                                  long *aChildIndex)
 {
 __try {
   *aChildIndex = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRInt32 childIndex = 0;
   nsresult rv = tableAcc->GetCellIndexAt(aRowIndex, aColumnIndex, &childIndex);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -175,17 +175,17 @@ CAccessibleTable::get_childIndex(long aR
 }
 
 STDMETHODIMP
 CAccessibleTable::get_columnDescription(long aColumn, BSTR *aDescription)
 {
 __try {
   *aDescription = NULL;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   nsAutoString descr;
   nsresult rv = tableAcc->GetColumnDescription (aColumn, descr);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -202,17 +202,17 @@ CAccessibleTable::get_columnDescription(
 
 STDMETHODIMP
 CAccessibleTable::get_columnExtentAt(long aRow, long aColumn,
                                      long *nColumnsSpanned)
 {
 __try {
   *nColumnsSpanned = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRInt32 columnsSpanned = 0;
   nsresult rv = tableAcc->GetColumnExtentAt(aRow, aColumn, &columnsSpanned);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -238,17 +238,17 @@ CAccessibleTable::get_columnHeader(IAcce
 }
 
 STDMETHODIMP
 CAccessibleTable::get_columnIndex(long aChildIndex, long *aColumnIndex)
 {
 __try {
   *aColumnIndex = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRInt32 columnIndex = 0;
   nsresult rv = tableAcc->GetColumnIndexAt(aChildIndex, &columnIndex);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -262,17 +262,17 @@ CAccessibleTable::get_columnIndex(long a
 }
 
 STDMETHODIMP
 CAccessibleTable::get_nColumns(long *aColumnCount)
 {
 __try {
   *aColumnCount = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRInt32 columnCount = 0;
   nsresult rv = tableAcc->GetColumnCount(&columnCount);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -286,17 +286,17 @@ CAccessibleTable::get_nColumns(long *aCo
 }
 
 STDMETHODIMP
 CAccessibleTable::get_nRows(long *aRowCount)
 {
 __try {
   *aRowCount = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRInt32 rowCount = 0;
   nsresult rv = tableAcc->GetRowCount(&rowCount);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -310,17 +310,17 @@ CAccessibleTable::get_nRows(long *aRowCo
 }
 
 STDMETHODIMP
 CAccessibleTable::get_nSelectedChildren(long *aChildCount)
 {
 __try {
   *aChildCount = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRUint32 count = 0;
   nsresult rv = tableAcc->GetSelectedCellCount(&count);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -333,17 +333,17 @@ CAccessibleTable::get_nSelectedChildren(
 }
 
 STDMETHODIMP
 CAccessibleTable::get_nSelectedColumns(long *aColumnCount)
 {
 __try {
   *aColumnCount = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRUint32 count = 0;
   nsresult rv = tableAcc->GetSelectedColumnCount(&count);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -356,17 +356,17 @@ CAccessibleTable::get_nSelectedColumns(l
 }
 
 STDMETHODIMP
 CAccessibleTable::get_nSelectedRows(long *aRowCount)
 {
 __try {
   *aRowCount = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRUint32 count = 0;
   nsresult rv = tableAcc->GetSelectedRowCount(&count);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -379,17 +379,17 @@ CAccessibleTable::get_nSelectedRows(long
 }
 
 STDMETHODIMP
 CAccessibleTable::get_rowDescription(long aRow, BSTR *aDescription)
 {
 __try {
   *aDescription = NULL;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   nsAutoString descr;
   nsresult rv = tableAcc->GetRowDescription (aRow, descr);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -405,17 +405,17 @@ CAccessibleTable::get_rowDescription(lon
 }
 
 STDMETHODIMP
 CAccessibleTable::get_rowExtentAt(long aRow, long aColumn, long *aNRowsSpanned)
 {
 __try {
   *aNRowsSpanned = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRInt32 rowsSpanned = 0;
   nsresult rv = tableAcc->GetRowExtentAt(aRow, aColumn, &rowsSpanned);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -441,17 +441,17 @@ CAccessibleTable::get_rowHeader(IAccessi
 }
 
 STDMETHODIMP
 CAccessibleTable::get_rowIndex(long aChildIndex, long *aRowIndex)
 {
 __try {
   *aRowIndex = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRInt32 rowIndex = 0;
   nsresult rv = tableAcc->GetRowIndexAt(aChildIndex, &rowIndex);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -515,17 +515,17 @@ CAccessibleTable::get_summary(IUnknown *
 }
 
 STDMETHODIMP
 CAccessibleTable::get_isColumnSelected(long aColumn, boolean *aIsSelected)
 {
 __try {
   *aIsSelected = false;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRBool isSelected = PR_FALSE;
   nsresult rv = tableAcc->IsColumnSelected(aColumn, &isSelected);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -538,17 +538,17 @@ CAccessibleTable::get_isColumnSelected(l
 }
 
 STDMETHODIMP
 CAccessibleTable::get_isRowSelected(long aRow, boolean *aIsSelected)
 {
 __try {
   *aIsSelected = false;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRBool isSelected = PR_FALSE;
   nsresult rv = tableAcc->IsRowSelected(aRow, &isSelected);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -561,17 +561,17 @@ CAccessibleTable::get_isRowSelected(long
 }
 
 STDMETHODIMP
 CAccessibleTable::get_isSelected(long aRow, long aColumn, boolean *aIsSelected)
 {
 __try {
   *aIsSelected = false;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRBool isSelected = PR_FALSE;
   nsresult rv = tableAcc->IsCellSelected(aRow, aColumn, &isSelected);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -582,65 +582,65 @@ CAccessibleTable::get_isSelected(long aR
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return E_FAIL;
 }
 
 STDMETHODIMP
 CAccessibleTable::selectRow(long aRow)
 {
 __try {
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   nsresult rv = tableAcc->SelectRow(aRow);
   return GetHRESULT(rv);
 
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return E_FAIL;
 }
 
 STDMETHODIMP
 CAccessibleTable::selectColumn(long aColumn)
 {
 __try {
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   nsresult rv = tableAcc->SelectColumn(aColumn);
   return GetHRESULT(rv);
 
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return E_FAIL;
 }
 
 STDMETHODIMP
 CAccessibleTable::unselectRow(long aRow)
 {
 __try {
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   nsresult rv = tableAcc->UnselectRow(aRow);
   return GetHRESULT(rv);
 
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return E_FAIL;
 }
 
 STDMETHODIMP
 CAccessibleTable::unselectColumn(long aColumn)
 {
 __try {
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   nsresult rv = tableAcc->UnselectColumn(aColumn);
   return GetHRESULT(rv);
 
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
@@ -656,17 +656,17 @@ CAccessibleTable::get_rowColumnExtentsAt
 {
 __try {
   *aRow = 0;
   *aColumn = 0;
   *aRowExtents = 0;
   *aColumnExtents = 0;
   *aIsSelected = false;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRInt32 row = -1;
   nsresult rv = tableAcc->GetRowIndexAt(aIndex, &row);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -725,17 +725,17 @@ CAccessibleTable::get_nSelectedCells(lon
 {
   return get_nSelectedChildren(cellCount);
 }
 
 STDMETHODIMP
 CAccessibleTable::get_selectedCells(IUnknown ***cells, long *nSelectedCells)
 {
 __try {
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   nsCOMPtr<nsIArray> geckoCells;
   nsresult rv = tableAcc->GetSelectedCells(getter_AddRefs(geckoCells));
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -774,17 +774,17 @@ CAccessibleTable::get_selectedRows(long 
 // CAccessibleTable public
 
 HRESULT
 CAccessibleTable::GetSelectedItems(long **aItems, long *aItemsCount,
                                    eItemsType aType)
 {
   *aItemsCount = 0;
 
-  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryObject(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
     return E_FAIL;
 
   PRUint32 size = 0;
   PRInt32 *items = nsnull;
 
   nsresult rv = NS_OK;
--- a/accessible/src/msaa/CAccessibleTable.h
+++ b/accessible/src/msaa/CAccessibleTable.h
@@ -41,18 +41,17 @@
 #ifndef _ACCESSIBLE_TABLE_H
 #define _ACCESSIBLE_TABLE_H
 
 #include "nsISupports.h"
 
 #include "AccessibleTable.h"
 #include "AccessibleTable2.h"
 
-class CAccessibleTable: public nsISupports,
-                        public IAccessibleTable,
+class CAccessibleTable: public IAccessibleTable,
                         public IAccessibleTable2
 {
 public:
 
   // IUnknown
   STDMETHODIMP QueryInterface(REFIID, void**);
 
   // IAccessibleTable
@@ -190,16 +189,19 @@ public:
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_selectedColumns(
       /* [out, size_is(,*nColumns)] */ long **selectedColumns,
       /* [out, retval] */ long *nColumns);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_selectedRows(
       /* [out, size_is(,*nRows)] */ long **selectedRows, 
       /* [out, retval] */ long *nRows);
 
+  // nsISupports
+  NS_IMETHOD QueryInterface(const nsIID& uuid, void** result) = 0;
+
 private:
   enum eItemsType {
     ITEMSTYPE_CELLS,
     ITEMSTYPE_COLUMNS,
     ITEMSTYPE_ROWS
   };
 
   HRESULT GetSelectedItems(long **aItems, long *aItemsCount, eItemsType aType);
--- a/accessible/src/msaa/CAccessibleTableCell.cpp
+++ b/accessible/src/msaa/CAccessibleTableCell.cpp
@@ -74,17 +74,17 @@ CAccessibleTableCell::QueryInterface(REF
 
 ////////////////////////////////////////////////////////////////////////////////
 // IAccessibleTableCell
 
 STDMETHODIMP
 CAccessibleTableCell::get_table(IUnknown **table)
 {
 __try {
-  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryObject(this));
   NS_ASSERTION(tableCell, TABLECELL_INTERFACE_UNSUPPORTED_MSG);
   if (!tableCell)
     return E_FAIL;
 
   nsCOMPtr<nsIAccessibleTable> geckoTable;
   nsresult rv = tableCell->GetTable(getter_AddRefs(geckoTable));
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -108,17 +108,17 @@ CAccessibleTableCell::get_table(IUnknown
 }
 
 STDMETHODIMP
 CAccessibleTableCell::get_columnExtent(long *nColumnsSpanned)
 {
 __try {
   *nColumnsSpanned = 0;
 
-  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryObject(this));
   NS_ASSERTION(tableCell, TABLECELL_INTERFACE_UNSUPPORTED_MSG);
   if (!tableCell)
     return E_FAIL;
 
   PRInt32 columnsSpanned = 0;
   nsresult rv = tableCell->GetColumnExtent(&columnsSpanned);
   if (NS_SUCCEEDED(rv)) {
     *nColumnsSpanned = columnsSpanned;
@@ -133,17 +133,17 @@ CAccessibleTableCell::get_columnExtent(l
   return E_FAIL;
 }
 
 STDMETHODIMP
 CAccessibleTableCell::get_columnHeaderCells(IUnknown ***cellAccessibles,
                                             long *nColumnHeaderCells)
 {
 __try {
-  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryObject(this));
   NS_ASSERTION(tableCell, TABLECELL_INTERFACE_UNSUPPORTED_MSG);
   if (!tableCell)
     return E_FAIL;
 
   nsCOMPtr<nsIArray> headerCells;
   nsresult rv = tableCell->GetColumnHeaderCells(getter_AddRefs(headerCells));  
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -158,17 +158,17 @@ CAccessibleTableCell::get_columnHeaderCe
 }
 
 STDMETHODIMP
 CAccessibleTableCell::get_columnIndex(long *columnIndex)
 {
 __try {
   *columnIndex = -1;
 
-  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryObject(this));
   NS_ASSERTION(tableCell, TABLECELL_INTERFACE_UNSUPPORTED_MSG);
   if (!tableCell)
     return E_FAIL;
 
   PRInt32 colIdx = -1;
   nsresult rv = tableCell->GetColumnIndex(&colIdx);
   if (NS_SUCCEEDED(rv)) {
     *columnIndex = colIdx;
@@ -184,17 +184,17 @@ CAccessibleTableCell::get_columnIndex(lo
 }
 
 STDMETHODIMP
 CAccessibleTableCell::get_rowExtent(long *nRowsSpanned)
 {
 __try {
   *nRowsSpanned = 0;
 
-  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryObject(this));
   NS_ASSERTION(tableCell, TABLECELL_INTERFACE_UNSUPPORTED_MSG);
   if (!tableCell)
     return E_FAIL;
 
   PRInt32 rowsSpanned = 0;
   nsresult rv = tableCell->GetRowExtent(&rowsSpanned);
   if (NS_SUCCEEDED(rv)) {
     *nRowsSpanned = rowsSpanned;
@@ -209,17 +209,17 @@ CAccessibleTableCell::get_rowExtent(long
   return E_FAIL;
 }
 
 STDMETHODIMP
 CAccessibleTableCell::get_rowHeaderCells(IUnknown ***cellAccessibles,
                                          long *nRowHeaderCells)
 {
 __try {
-  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryObject(this));
   NS_ASSERTION(tableCell, TABLECELL_INTERFACE_UNSUPPORTED_MSG);
   if (!tableCell)
     return E_FAIL;
 
   nsCOMPtr<nsIArray> headerCells;
   nsresult rv = tableCell->GetRowHeaderCells(getter_AddRefs(headerCells));  
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -234,17 +234,17 @@ CAccessibleTableCell::get_rowHeaderCells
 }
 
 STDMETHODIMP
 CAccessibleTableCell::get_rowIndex(long *rowIndex)
 {
 __try {
   *rowIndex = -1;
 
-  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryObject(this));
   NS_ASSERTION(tableCell, TABLECELL_INTERFACE_UNSUPPORTED_MSG);
   if (!tableCell)
     return E_FAIL;
 
   PRInt32 rowIdx = -1;
   nsresult rv = tableCell->GetRowIndex(&rowIdx);
   if (NS_SUCCEEDED(rv)) {
     *rowIndex = rowIdx;
@@ -267,17 +267,17 @@ CAccessibleTableCell::get_rowColumnExten
 {
 __try {
   *row = 0;
   *column = 0;
   *rowExtents = 0;
   *columnExtents = 0;
   *isSelected = false;
 
-  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryObject(this));
   NS_ASSERTION(tableCell, TABLECELL_INTERFACE_UNSUPPORTED_MSG);
   if (!tableCell)
     return E_FAIL;
 
   PRInt32 rowIdx = -1;
   nsresult rv = tableCell->GetRowIndex(&rowIdx);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
@@ -315,17 +315,17 @@ CAccessibleTableCell::get_rowColumnExten
 }
 
 STDMETHODIMP
 CAccessibleTableCell::get_isSelected(boolean *isSelected)
 {
 __try {
   *isSelected = false;
 
-  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleTableCell> tableCell(do_QueryObject(this));
   NS_ASSERTION(tableCell, TABLECELL_INTERFACE_UNSUPPORTED_MSG);
   if (!tableCell)
     return E_FAIL;
 
   PRBool isSel = PR_FALSE;
   nsresult rv = tableCell->IsSelected(&isSel);
   if (NS_SUCCEEDED(rv)) {
     *isSelected = isSel;
--- a/accessible/src/msaa/CAccessibleTableCell.h
+++ b/accessible/src/msaa/CAccessibleTableCell.h
@@ -40,18 +40,17 @@
 
 #ifndef _ACCESSIBLE_TABLECELL_H
 #define _ACCESSIBLE_TABLECELL_H
 
 #include "nsISupports.h"
 
 #include "AccessibleTableCell.h"
 
-class CAccessibleTableCell: public nsISupports,
-                            public IAccessibleTableCell
+class CAccessibleTableCell: public IAccessibleTableCell
 {
 public:
 
   // IUnknown
   STDMETHODIMP QueryInterface(REFIID, void**);
 
   // IAccessibleTableCell
 
@@ -82,11 +81,14 @@ public:
       /* [out] */ long *row,
       /* [out] */ long *column,
       /* [out] */ long *rowExtents,
       /* [out] */ long *columnExtents,
       /* [out, retval] */ boolean *isSelected);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_isSelected(
       /* [out, retval] */ boolean *isSelected);
+
+  // nsISupports
+  NS_IMETHOD QueryInterface(const nsIID& uuid, void** result) = 0;
 };
 
 #endif
--- a/accessible/src/msaa/CAccessibleText.cpp
+++ b/accessible/src/msaa/CAccessibleText.cpp
@@ -50,31 +50,31 @@
 #include "nsAccessNodeWrap.h"
 #include "nsAccessibleWrap.h"
 
 #include "nsCOMPtr.h"
 #include "nsIPersistentProperties2.h"
 #include "nsString.h"
 
 #define GET_NSIACCESSIBLETEXT \
-nsCOMPtr<nsIAccessibleText> textAcc(do_QueryInterface(this));\
+nsCOMPtr<nsIAccessibleText> textAcc(do_QueryObject(this));\
 NS_ASSERTION(textAcc,\
              "Subclass of CAccessibleText doesn't implement nsIAccessibleText");\
 if (!textAcc)\
   return E_FAIL;\
 
 // IUnknown
 
 STDMETHODIMP
 CAccessibleText::QueryInterface(REFIID iid, void** ppv)
 {
   *ppv = NULL;
 
   if (IID_IAccessibleText == iid) {
-    nsCOMPtr<nsIAccessibleText> textAcc(do_QueryInterface(this));
+    nsCOMPtr<nsIAccessibleText> textAcc(do_QueryObject(this));
     if (!textAcc) {
       return E_NOINTERFACE;
     }
     *ppv = static_cast<IAccessibleText*>(this);
     (reinterpret_cast<IUnknown*>(*ppv))->AddRef();
     return S_OK;
   }
 
--- a/accessible/src/msaa/CAccessibleText.h
+++ b/accessible/src/msaa/CAccessibleText.h
@@ -41,18 +41,17 @@
 #ifndef _ACCESSIBLE_TEXT_H
 #define _ACCESSIBLE_TEXT_H
 
 #include "nsISupports.h"
 #include "nsIAccessibleText.h"
 
 #include "AccessibleText.h"
 
-class CAccessibleText: public nsISupports,
-                       public IAccessibleText
+class CAccessibleText: public IAccessibleText
 {
 public:
 
   // IUnknown
   STDMETHODIMP QueryInterface(REFIID, void**);
 
   // IAccessibleText
   virtual HRESULT STDMETHODCALLTYPE addSelection(
@@ -143,16 +142,19 @@ public:
       /* [in] */ long y);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_newText(
       /* [retval][out] */ IA2TextSegment *newText);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_oldText(
       /* [retval][out] */ IA2TextSegment *oldText);
 
+  // nsISupports
+  NS_IMETHOD QueryInterface(const nsIID& uuid, void** result) = 0;
+
 protected:
   virtual nsresult GetModifiedText(PRBool aGetInsertedText, nsAString& aText,
                                    PRUint32 *aStartOffset,
                                    PRUint32 *aEndOffset) = 0;
 
 private:
   HRESULT GetModifiedText(PRBool aGetInsertedText, IA2TextSegment *aNewText);
   nsAccessibleTextBoundary GetGeckoTextBoundary(enum IA2TextBoundaryType coordinateType);
--- a/accessible/src/msaa/CAccessibleValue.cpp
+++ b/accessible/src/msaa/CAccessibleValue.cpp
@@ -51,17 +51,17 @@
 // IUnknown
 
 STDMETHODIMP
 CAccessibleValue::QueryInterface(REFIID iid, void** ppv)
 {
   *ppv = NULL;
 
   if (IID_IAccessibleValue == iid) {
-    nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryInterface(this));
+    nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryObject(this));
     if (!valueAcc)
       return E_NOINTERFACE;
 
     *ppv = static_cast<IAccessibleValue*>(this);
     (reinterpret_cast<IUnknown*>(*ppv))->AddRef();
     return S_OK;
   }
 
@@ -71,17 +71,17 @@ CAccessibleValue::QueryInterface(REFIID 
 // IAccessibleValue
 
 STDMETHODIMP
 CAccessibleValue::get_currentValue(VARIANT *aCurrentValue)
 {
 __try {
   VariantInit(aCurrentValue);
 
-  nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryObject(this));
   if (!valueAcc)
     return E_FAIL;
 
   double currentValue = 0;
   nsresult rv = valueAcc->GetCurrentValue(&currentValue);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
@@ -92,17 +92,17 @@ CAccessibleValue::get_currentValue(VARIA
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return E_FAIL;
 }
 
 STDMETHODIMP
 CAccessibleValue::setCurrentValue(VARIANT aValue)
 {
 __try {
-  nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryObject(this));
   if (!valueAcc)
     return E_FAIL;
 
   if (aValue.vt != VT_R8)
     return E_INVALIDARG;
 
   nsresult rv = valueAcc->SetCurrentValue(aValue.dblVal);
   return GetHRESULT(rv);
@@ -112,17 +112,17 @@ CAccessibleValue::setCurrentValue(VARIAN
 }
 
 STDMETHODIMP
 CAccessibleValue::get_maximumValue(VARIANT *aMaximumValue)
 {
 __try {
   VariantInit(aMaximumValue);
 
-  nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryObject(this));
   if (!valueAcc)
     return E_FAIL;
 
   double maximumValue = 0;
   nsresult rv = valueAcc->GetMaximumValue(&maximumValue);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
@@ -135,17 +135,17 @@ CAccessibleValue::get_maximumValue(VARIA
 }
 
 STDMETHODIMP
 CAccessibleValue::get_minimumValue(VARIANT *aMinimumValue)
 {
 __try {
   VariantInit(aMinimumValue);
 
-  nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryInterface(this));
+  nsCOMPtr<nsIAccessibleValue> valueAcc(do_QueryObject(this));
   if (!valueAcc)
     return E_FAIL;
 
   double minimumValue = 0;
   nsresult rv = valueAcc->GetMinimumValue(&minimumValue);
   if (NS_FAILED(rv))
     return GetHRESULT(rv);
 
--- a/accessible/src/msaa/CAccessibleValue.h
+++ b/accessible/src/msaa/CAccessibleValue.h
@@ -40,18 +40,17 @@
 
 #ifndef _ACCESSIBLE_VALUE_H
 #define _ACCESSIBLE_VALUE_H
 
 #include "nsISupports.h"
 
 #include "AccessibleValue.h"
 
-class CAccessibleValue: public nsISupports,
-                        public IAccessibleValue
+class CAccessibleValue: public IAccessibleValue
 {
 public:
 
   // IUnknown
   STDMETHODIMP QueryInterface(REFIID, void**);
 
   // IAccessibleValue
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_currentValue(
@@ -61,12 +60,15 @@ public:
       /* [in] */ VARIANT value);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_maximumValue(
       /* [retval][out] */ VARIANT *maximumValue);
 
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_minimumValue(
       /* [retval][out] */ VARIANT *minimumValue);
 
+  // nsISupports
+  NS_IMETHOD QueryInterface(const nsIID& uuid, void** result) = 0;
+
 };
 
 #endif
 
--- a/accessible/src/msaa/nsAccessNodeWrap.h
+++ b/accessible/src/msaa/nsAccessNodeWrap.h
@@ -161,17 +161,16 @@ public: // construction, destruction
 
     static PRBool IsOnlyMsaaCompatibleJawsPresent();
 
     static void TurnOffNewTabSwitchingForJawsAndWE();
 
     static void DoATSpecificProcessing();
 
 protected:
-    void GetAccessibleFor(nsIDOMNode *node, nsIAccessible **newAcc);
 
   /**
    * Return ISimpleDOMNode instance for existing accessible object or
    * creates new nsAccessNode instance if the accessible doesn't exist.
    *
    * @note ISimpleDOMNode is returned addrefed
    */
   ISimpleDOMNode *MakeAccessNode(nsINode *aNode);
--- a/accessible/src/xforms/nsXFormsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsAccessible.cpp
@@ -393,17 +393,16 @@ nsXFormsSelectableAccessible::GetSelecte
 NS_IMETHODIMP
 nsXFormsSelectableAccessible::GetSelectionCount(PRInt32 *aCount)
 {
   NS_ENSURE_ARG_POINTER(aCount);
 
   *aCount = 0;
 
   nsresult rv;
-  PRBool thisLineWasReviewedByDavid = PR_FALSE;
   nsCOMPtr<nsIDOMNode> DOMNode(do_QueryInterface(mContent));
 
   if (mIsSelect1Element) {
     nsCOMPtr<nsIDOMNode> item;
     rv = sXFormsService->GetSelectedItemForSelect1(DOMNode,
                                                    getter_AddRefs(item));
     NS_ENSURE_SUCCESS(rv, rv);
 
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -1119,17 +1119,18 @@ nsXULTreeItemAccessibleBase::IsExpandabl
     PRBool isEmpty = PR_FALSE;
     mTreeView->IsContainerEmpty(mRow, &isEmpty);
     if (!isEmpty) {
       nsCOMPtr<nsITreeColumns> columns;
       mTree->GetColumns(getter_AddRefs(columns));
       nsCOMPtr<nsITreeColumn> primaryColumn;
       if (columns) {
         columns->GetPrimaryColumn(getter_AddRefs(primaryColumn));
-        if (!nsCoreUtils::IsColumnHidden(primaryColumn))
+        if (primaryColumn &&
+            !nsCoreUtils::IsColumnHidden(primaryColumn))
           return PR_TRUE;
       }
     }
   }
 
   return PR_FALSE;
 }
 
--- a/browser/app/profile/extensions/testpilot@labs.mozilla.com/defaults/preferences/preferences.js
+++ b/browser/app/profile/extensions/testpilot@labs.mozilla.com/defaults/preferences/preferences.js
@@ -11,10 +11,10 @@ pref("extensions.testpilot.alwaysSubmitD
 pref("extensions.testpilot.runStudies", true);
 
 pref("extensions.testpilot.indexBaseURL", "https://testpilot.mozillalabs.com/testcases/");
 pref("extensions.testpilot.firstRunUrl", "chrome://testpilot/content/welcome.html");
 pref("extensions.testpilot.dataUploadURL", "https://testpilot.mozillalabs.com/submit/");
 pref("extensions.testpilot.homepageURL", "https://testpilot.mozillalabs.com/");
 
 
-pref("extensions.input.happyURL", "http://input.mozilla.com/happy");
-pref("extensions.input.sadURL", "http://input.mozilla.com/sad");
+pref("extensions.input.happyURL", "https://input.mozilla.com/happy");
+pref("extensions.input.sadURL", "https://input.mozilla.com/sad");
--- a/browser/base/content/browser-places.js
+++ b/browser/base/content/browser-places.js
@@ -1157,17 +1157,17 @@ let BookmarksMenuButton = {
     bookmarksToolbarElt.collapsed =
       this.button.parentNode == this.bookmarksToolbarItem;
   },
 
   updatePosition: function BMB_updatePosition() {
     this._popupNeedsUpdating = true;
 
     let bookmarksToolbarItem = this.bookmarksToolbarItem;
-    if (isElementVisible(bookmarksToolbarItem)) {
+    if (bookmarksToolbarItem && !bookmarksToolbarItem.parentNode.collapsed) {
       if (this.button.parentNode != bookmarksToolbarItem) {
         this.resetView();
         bookmarksToolbarItem.appendChild(this.button);
       }
       this.button.classList.add("bookmark-item");
       this.button.classList.remove("toolbarbutton-1");
     }
     else {
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -196,17 +196,18 @@ richlistitem[type="action"]:-moz-locale-
 }
 
 toolbarbutton.bookmark-item {
   max-width: 13em;
 }
 
 %ifdef MENUBAR_CAN_AUTOHIDE
 #toolbar-menubar:not([autohide="true"]) ~ #nav-bar > #bookmarks-menu-button-container,
-#toolbar-menubar:not([autohide="true"]) ~ toolbar > #personal-bookmarks > #bookmarks-menu-button {
+#toolbar-menubar:not([autohide="true"]) ~ toolbar > #personal-bookmarks > #bookmarks-menu-button,
+#toolbar-menubar:not([autohide="true"]) > #personal-bookmarks > #bookmarks-menu-button {
   display: none;
 }
 %endif
 
 #editBMPanel_tagsSelector {
   /* override default listbox width from xul.css */
   width: auto;
 }
@@ -311,8 +312,18 @@ window[chromehidden~="toolbar"] toolbar:
 }
 
 /* Inspector / Highlighter */
 
 #highlighter-panel {
   -moz-appearance: none;
   -moz-window-shadow: none;
 }
+
+/* notification anchors should only be visible when their associated
+   notifications are */
+.notification-anchor-icon {
+  display: none;
+}
+
+#notification-popup-box[anchorid="geo-notification-icon"] > #geo-notification-icon {
+  display: -moz-box;
+}
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -2668,17 +2668,21 @@ function FillInHTMLTooltip(tipElement)
     return retVal;
 
   const XLinkNS = "http://www.w3.org/1999/xlink";
 
 
   var titleText = null;
   var XLinkTitleText = null;
   var SVGTitleText = null;
+#ifdef MOZ_SVG
   var lookingForSVGTitle = true;
+#else
+  var lookingForSVGTitle = false;
+#endif // MOZ_SVG
   var direction = tipElement.ownerDocument.dir;
 
   while (!titleText && !XLinkTitleText && !SVGTitleText && tipElement) {
     if (tipElement.nodeType == Node.ELEMENT_NODE) {
       titleText = tipElement.getAttribute("title");
       if ((tipElement instanceof HTMLAnchorElement && tipElement.href) ||
           (tipElement instanceof HTMLAreaElement && tipElement.href) ||
           (tipElement instanceof HTMLLinkElement && tipElement.href)
@@ -4099,17 +4103,21 @@ var XULBrowserWindow = {
       if (newIndexOfHash != -1)
         newSpec = newSpec.substr(0, newSpec.indexOf("#"));
       if (newSpec != oldSpec) {
         // Remove all the notifications, except for those which want to
         // persist across the first location change.
         let nBox = gBrowser.getNotificationBox(selectedBrowser);
         nBox.removeTransientNotifications();
 
-        PopupNotifications.locationChange();
+        // Only need to call locationChange if the PopupNotifications object
+        // for this window has already been initialized (i.e. its getter no
+        // longer exists)
+        if (!__lookupGetter__("PopupNotifications"))
+          PopupNotifications.locationChange();
       }
     }
 
     // Disable menu entries for images, enable otherwise
     if (content.document && mimeTypeIsTextBased(content.document.contentType))
       this.isImage.removeAttribute('disabled');
     else
       this.isImage.setAttribute('disabled', 'true');
@@ -4625,28 +4633,31 @@ var TabsOnTop = {
   },
   get enabled () {
     return gNavToolbox.getAttribute("tabsontop") == "true";
   },
   set enabled (val) {
     gNavToolbox.setAttribute("tabsontop", !!val);
     this.syncCommand();
 
-    //XXX: Trigger reframe. This is a workaround for bug 555987 and needs to be
-    //     removed once that bug is fixed.
-    gNavToolbox.style.MozBoxOrdinalGroup = val ? 2 : 3;
-
     return val;
   }
 }
 
 #ifdef MENUBAR_CAN_AUTOHIDE
 function updateAppButtonDisplay() {
-  document.getElementById("appmenu-button-container").hidden =
-    document.getElementById("toolbar-menubar").getAttribute("autohide") != "true";
+  var menubarHidden =
+    document.getElementById("toolbar-menubar").getAttribute("autohide") == "true";
+
+  document.getElementById("appmenu-button-container").hidden = !menubarHidden;
+
+  if (menubarHidden)
+    document.documentElement.setAttribute("chromemargin", "0,-1,-1,-1");
+  else
+    document.documentElement.removeAttribute("chromemargin");
 }
 #endif
 
 function displaySecurityInfo()
 {
   BrowserPageInfo(null, "securityTab");
 }
 
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -386,46 +386,43 @@
   <hbox id="appmenu-button-container">
     <button id="appmenu-button"
             type="menu"
             label="&brandShortName;"
             style="-moz-user-focus: ignore;">
       <menupopup>
         <menuitem id="appmenu_newNavigator"
                   label="&newNavigatorCmd.label;"
-                  key="key_newNavigator"
                   command="cmd_newNavigator"/>
         <menuseparator/>
         <menuitem id="appmenu_savePage"
                   label="&savePageCmd.label;"
-                  key="key_savePage"
                   command="Browser:SavePage"/>
         <menuitem id="appmenu_sendLink"
                   label="&sendPageCmd.label;"
                   command="Browser:SendLink"/>
-        <hbox flex="1">
+        <hbox flex="1" class="split-menuitem">
           <menuitem id="appmenu_print"
+                    class="split-menuitem-item"
                     flex="1"
                     label="&appMenuPrintCmd.label;"
-                    key="printKb"
                     command="cmd_print"/>
           <menu class="split-menuitem-menu">
             <menupopup>
               <menuitem id="menu_printSetup"
                         label="&printSetupCmd.label;"
                         command="cmd_pageSetup"/>
               <menuitem id="menu_printPreview"
                         label="&printPreviewCmd.label;"
                         command="cmd_printPreview"/>
             </menupopup>
           </menu>
         </hbox>
         <menuitem id="appmenu_find"
                   label="&findOnCmd.label;"
-                  key="key_find"
                   command="cmd_find"/>
         <menuseparator/>
         <menu id="appmenu_history"
               label="&historyMenu.label;">
           <menupopup id="appmenu_history_popup"
                      placespopup="true"
                      oncommand="this.parentNode._placesView._onCommand(event);"
                      onclick="checkForMiddleClick(this, event);"
@@ -487,19 +484,16 @@
                   oncommand="openHelpLink('firefox-help')"
                   onclick="checkForMiddleClick(this, event);"/>
         <menuseparator/>
         <menuitem id="appmenu_quit"
 #ifdef XP_WIN
                   label="&quitApplicationCmdWin.label;"
 #else
                   label="&quitApplicationCmd.label;"
-#ifdef XP_UNIX
-                  key="key_quitApplication"
-#endif
 #endif
                   command="cmd_quitApplication"/>
       </menupopup>
     </button>
   </hbox>
 #endif
 
   <toolbox id="navigator-toolbox"
@@ -608,17 +602,17 @@
                  ontextentered="this.handleCommand(param);"
                  ontextreverted="return this.handleRevert();"
                  pageproxystate="invalid"
                  onsearchbegin="LocationBarHelpers._searchBegin();"
                  onsearchcomplete="LocationBarHelpers._searchComplete();"
                  onfocus="document.getElementById('identity-box').style.MozUserFocus= 'normal'"
                  onblur="setTimeout(function() document.getElementById('identity-box').style.MozUserFocus = '', 0);">
           <box id="notification-popup-box" hidden="true" align="center">
-            <image id="geo-notification-icon"/>
+            <image id="geo-notification-icon" class="notification-anchor-icon"/>
           </box>
           <!-- Use onclick instead of normal popup= syntax since the popup
                code fires onmousedown, and hence eats our favicon drag events.
                We only add the identity-box button to the tab order when the location bar
                has focus, otherwise pressing F6 focuses it instead of the location bar -->
           <box id="identity-box" role="button"
                onclick="gIdentityHandler.handleIdentityButtonEvent(event);"
                onkeypress="gIdentityHandler.handleIdentityButtonEvent(event);">
@@ -788,17 +782,17 @@
                            class="chevron"
                            mousethrough="never"
                            collapsed="true"
                            tooltiptext="&bookmarksToolbarChevron.tooltip;"
                            onpopupshowing="document.getElementById('PlacesToolbar')
                                                    ._placesView._onChevronPopupShowing(event);">
               <menupopup id="PlacesChevronPopup"
                          placespopup="true"
-                         popupsinherittooltip="true"
+                         tooltip="bhTooltip" popupsinherittooltip="true"
                          context="placesContext"/>
             </toolbarbutton>
           </hbox>
         </hbox>
       </toolbaritem>
     </toolbar>
 
     <toolbar id="TabsToolbar"
--- a/browser/base/content/test/browser_drag.js
+++ b/browser/base/content/test/browser_drag.js
@@ -32,10 +32,10 @@ function test()
   var browser = gBrowser.getBrowserForTab(tab);
 
   browser.addEventListener("load", function () {
     is(browser.contentWindow.location, "http://mochi.test:8888/", "drop on tab");
     gBrowser.removeTab(tab);
     finish();
   }, true);
 
-  EventUtils.synthesizeDrop(tab, [[{type: "text/uri-list", data: "http://mochi.test:8888/"}]], "copy", window);
+  EventUtils.synthesizeDrop(tab, tab, [[{type: "text/uri-list", data: "http://mochi.test:8888/"}]], "copy", window);
 }
--- a/browser/base/content/test/browser_popupNotification.js
+++ b/browser/base/content/test/browser_popupNotification.js
@@ -298,16 +298,18 @@ var tests = [
       this.notifyObj2.id += "-2";
       this.notifyObj2.anchorID = "urlbar";
       // Second showNotification() overrides the first
       this.secondNotification = showNotification(this.notifyObj2);
     },
     onShown: function (popup) {
       // This also checks that only one element is shown.
       checkPopup(popup, this.notifyObj2);
+      is(document.getElementById("geo-notification-icon").boxObject.width, 0,
+         "geo anchor shouldn't be visible");
       dismissNotification(popup);
     },
     onHidden: function (popup) {
       // Remove the first notification
       this.firstNotification.remove();
     }
   },
   // Test optional params
@@ -320,16 +322,33 @@ var tests = [
     onShown: function (popup) {
       checkPopup(popup, this.notifyObj);
       dismissNotification(popup);
     },
     onHidden: function (popup) {
       this.notification.remove();
     }
   },
+  // Test that anchor icon appears
+  { // Test #11
+    run: function () {
+      this.notifyObj = new basicNotification();
+      this.notifyObj.anchorID = "geo-notification-icon";
+      this.notification = showNotification(this.notifyObj);
+    },
+    onShown: function (popup) {
+      checkPopup(popup, this.notifyObj);
+      isnot(document.getElementById("geo-notification-icon").boxObject.width, 0,
+            "geo anchor should be visible");
+      dismissNotification(popup);
+    },
+    onHidden: function (popup) {
+      this.notification.remove();
+    }
+  },
 ];
 
 function showNotification(notifyObj) {
   return PopupNotifications.show(notifyObj.browser,
                                  notifyObj.id,
                                  notifyObj.message,
                                  notifyObj.anchorID,
                                  notifyObj.mainAction,
new file mode 100644
--- /dev/null
+++ b/browser/base/content/win6BrowserOverlay.xul
@@ -0,0 +1,44 @@
+<?xml version="1.0"?>
+# -*- Mode: HTML -*-
+#
+# ***** 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) 2010
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#   Dão Gottwald <dao@mozilla.com> (Original Author)
+#
+# 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 *****
+
+<overlay id="win6-browser-overlay"
+         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+  <toolbar id="toolbar-menubar"
+           autohide="true"/>
+</overlay>
--- a/browser/base/jar.mn
+++ b/browser/base/jar.mn
@@ -1,16 +1,19 @@
 browser.jar:
 %  content browser %content/browser/ contentaccessible=yes
 #ifdef XP_MACOSX
 %  overlay chrome://mozapps/content/downloads/downloads.xul chrome://browser/content/downloadManagerOverlay.xul
 %  overlay chrome://mozapps/content/extensions/extensions.xul chrome://browser/content/extensionsManagerOverlay.xul
 %  overlay chrome://global/content/console.xul chrome://browser/content/jsConsoleOverlay.xul
 %  overlay chrome://mozapps/content/update/updates.xul chrome://browser/content/softwareUpdateOverlay.xul
 #endif
+#ifdef XP_WIN
+%  overlay chrome://browser/content/browser.xul chrome://browser/content/win6BrowserOverlay.xul os=WINNT osversion>=6
+#endif
 %  overlay chrome://global/content/viewSource.xul chrome://browser/content/viewSourceOverlay.xul
 %  overlay chrome://global/content/viewPartialSource.xul chrome://browser/content/viewSourceOverlay.xul
 %  style chrome://global/content/customizeToolbar.xul chrome://browser/content/browser.css
 %  style chrome://global/content/customizeToolbar.xul chrome://browser/skin/
 *       content/browser/aboutDialog.xul               (content/aboutDialog.xul)
 *       content/browser/aboutDialog.js                (content/aboutDialog.js)
         content/browser/aboutDialog.css               (content/aboutDialog.css)
 *       content/browser/aboutRobots.xhtml             (content/aboutRobots.xhtml)
@@ -54,11 +57,14 @@ browser.jar:
 #ifdef XP_MACOSX
 *       content/browser/macBrowserOverlay.xul         (content/macBrowserOverlay.xul)
 *       content/browser/downloadManagerOverlay.xul    (content/downloadManagerOverlay.xul)
 *       content/browser/extensionsManagerOverlay.xul  (content/extensionsManagerOverlay.xul)
 *       content/browser/jsConsoleOverlay.xul          (content/jsConsoleOverlay.xul)
 *       content/browser/softwareUpdateOverlay.xul  (content/softwareUpdateOverlay.xul)
 #endif
 *       content/browser/viewSourceOverlay.xul         (content/viewSourceOverlay.xul)
+#ifdef XP_WIN
+*       content/browser/win6BrowserOverlay.xul        (content/win6BrowserOverlay.xul)
+#endif
 # the following files are browser-specific overrides
 *       content/browser/license.html                  (/toolkit/content/license.html)
 % override chrome://global/content/license.html chrome://browser/content/license.html
--- a/browser/components/search/test/browser_426329.js
+++ b/browser/components/search/test/browser_426329.js
@@ -132,35 +132,35 @@ function test() {
   // prevent the search buttonmenu from opening during the drag tests
   function stopPopup(event) { event.preventDefault(); }
 
   function testDropText() {
     init();
     searchBar.addEventListener("popupshowing", stopPopup, true);
     // drop on the search button so that we don't need to worry about the
     // default handlers for textboxes.
-    EventUtils.synthesizeDrop(searchBar.searchButton, [[ {type: "text/plain", data: "Some Text" } ]], "copy", window);
+    EventUtils.synthesizeDrop(searchBar.searchButton, searchBar.searchButton, [[ {type: "text/plain", data: "Some Text" } ]], "copy", window);
     doOnloadOnce(function(event) {
       is(searchBar.value, "Some Text", "drop text/plain on searchbar");
       testDropInternalText();
     });
   }
 
   function testDropInternalText() {
     init();
-    EventUtils.synthesizeDrop(searchBar.searchButton, [[ {type: "text/x-moz-text-internal", data: "More Text" } ]], "copy", window);
+    EventUtils.synthesizeDrop(searchBar.searchButton, searchBar.searchButton, [[ {type: "text/x-moz-text-internal", data: "More Text" } ]], "copy", window);
     doOnloadOnce(function(event) {
       is(searchBar.value, "More Text", "drop text/x-moz-text-internal on searchbar");
       testDropLink();
     });
   }
 
   function testDropLink() {
     init();
-    EventUtils.synthesizeDrop(searchBar.searchButton, [[ {type: "text/uri-list", data: "http://www.mozilla.org" } ]], "copy", window);
+    EventUtils.synthesizeDrop(searchBar.searchButton, searchBar.searchButton, [[ {type: "text/uri-list", data: "http://www.mozilla.org" } ]], "copy", window);
     is(searchBar.value, "More Text", "drop text/uri-list on searchbar");
     SimpleTest.executeSoon(testRightClick);
   }
   
   function testRightClick() {
     init();
     searchBar.removeEventListener("popupshowing", stopPopup, true);
     content.location.href = "about:blank";
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -175,16 +175,17 @@
 @BINPATH@/components/fuel.xpt
 @BINPATH@/components/gfx.xpt
 @BINPATH@/components/htmlparser.xpt
 @BINPATH@/components/imglib2.xpt
 @BINPATH@/components/imgicon.xpt
 @BINPATH@/components/inspector.xpt
 @BINPATH@/components/intl.xpt
 @BINPATH@/components/jar.xpt
+@BINPATH@/components/jetpack.xpt
 @BINPATH@/components/jsdservice.xpt
 @BINPATH@/components/layout_base.xpt
 #ifdef NS_PRINTING
 @BINPATH@/components/layout_printing.xpt
 #endif
 @BINPATH@/components/layout_xul_tree.xpt
 @BINPATH@/components/layout_xul.xpt
 @BINPATH@/components/locale.xpt
--- a/browser/locales/en-US/chrome/browser/browser.properties
+++ b/browser/locales/en-US/chrome/browser/browser.properties
@@ -8,17 +8,19 @@ dropondownloadsbutton=Drop a link or fil
 droponnewtabbutton=Drop a link or file to open it in a new tab
 droponnewwindowbutton=Drop a link or file to open it in a new window
 droponhomebutton=Drop a link or file to make it your home page
 droponhometitle=Set Home Page
 droponhomemsg=Do you want this document to be your new home page?
 
 # context menu strings
 
-contextMenuSearchText=Search %S for "%S"
+# LOCALIZATION NOTE (contextMenuSearchText): %1$S is the search engine,
+# %2$S is the selection string.
+contextMenuSearchText=Search %1$S for "%2$S"
 contextMenuSearchText.accesskey=S
 
 blockImages=Block Images from %S
 
 # bookmark dialog strings
 
 bookmarkAllTabsDefault=[Folder Name]
 
--- a/browser/themes/gnomestripe/browser/browser.css
+++ b/browser/themes/gnomestripe/browser/browser.css
@@ -575,17 +575,17 @@ toolbar[mode="full"] .toolbarbutton-menu
 #bookmarks-menu-button {
   -moz-image-region: rect(0px 72px 24px 48px);
 }
 
 #bookmarks-menu-button.bookmark-item {
   list-style-image: url("chrome://browser/skin/Toolbar-small.png");
 }
 
-toolbar[mode="icons"] #bookmarks-menu-button.toolbarbutton-1 {
+#bookmarks-menu-button.toolbarbutton-1 {
   -moz-box-orient: horizontal;
 }
 
 #print-button {
   list-style-image: url("moz-icon://stock/gtk-print?size=toolbar");
 }
 #print-button[disabled="true"] {
   list-style-image: url("moz-icon://stock/gtk-print?size=toolbar&state=disabled");
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -323,24 +323,18 @@ toolbar[mode="icons"] #restore-button,
 toolbar[mode="icons"] toolbarbutton[type="menu-button"] > .toolbarbutton-menubutton-button {
   min-width: 28px;
 }
 
 .toolbarbutton-1 > .toolbarbutton-icon,
 #restore-button > .toolbarbutton-icon,
 toolbarbutton[type="menu-button"] > .toolbarbutton-menubutton-button > .toolbarbutton-icon {
   padding: 0;
-  max-height: 20px;
-}
-
-/* Only set the max-width in icon-only mode because it affects the label, too */
-toolbar[mode="icons"] .toolbarbutton-1 > .toolbarbutton-icon,
-toolbar[mode="icons"] #restore-button > .toolbarbutton-icon,
-toolbar[mode="icons"] toolbarbutton[type="menu-button"] > .toolbarbutton-menubutton-button > .toolbarbutton-icon {
-  max-width: 20px;
+  height: 20px;
+  width: 20px;
 }
 
 .toolbarbutton-1[disabled="true"] > .toolbarbutton-icon,
 #restore-button[disabled="true"] > .toolbarbutton-icon,
 toolbarbutton[type="menu-button"] > .toolbarbutton-menubutton-button[disabled="true"] > .toolbarbutton-icon {
   opacity: .4;
 }
 
@@ -573,17 +567,17 @@ toolbar[iconsize="small"][mode="icons"] 
 #bookmarks-button[checked="true"]:active:hover {
   -moz-image-region: rect(40px, 180px, 60px, 160px);
 }
 
 #bookmarks-menu-button.bookmark-item {
   list-style-image: url("chrome://browser/skin/Toolbar.png");
 }
 
-toolbar[mode="icons"] #bookmarks-menu-button.toolbarbutton-1 {
+#bookmarks-menu-button.toolbarbutton-1 {
   -moz-box-orient: horizontal;
 }
 
 /* print button */
 
 #print-button {
   -moz-image-region: rect(0, 200px, 20px, 180px);
 }
--- a/browser/themes/winstripe/browser/browser-aero.css
+++ b/browser/themes/winstripe/browser/browser-aero.css
@@ -19,16 +19,21 @@
 }
 
 @media all and (-moz-windows-compositor) {
   #main-window:not(:-moz-lwtheme) {
     -moz-appearance: -moz-win-glass;
     background: transparent;
   }
 
+  /* the new titlebar requires this, or content will be clipped at the top of the screen. */
+  #main-window[sizemode="maximized"] {
+    margin-top: 8px;
+  }
+
   #main-window:not(:-moz-lwtheme)[inFullscreen="true"] {
     -moz-appearance: none;
     background-color: #556;
   }
 
   #toolbar-menubar:not(:-moz-lwtheme),
   #navigator-toolbox[tabsontop="true"] > #TabsToolbar:not(:-moz-lwtheme),
   #navigator-toolbox:not([tabsontop="true"]) > #nav-bar:not(:-moz-lwtheme),
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -119,22 +119,25 @@ statusbarpanel#statusbar-display {
 #appmenu-button {
   -moz-appearance: none;
   background-color: rgb(228,120,14);
   background-image: -moz-linear-gradient(rgba(255,255,255,.7),
                                          rgba(255,255,255,.4) 10%,
                                          rgba(255,255,255,0) 50%);
   background-clip: padding-box;
   border: 1px solid rgba(0,0,0,.5);
-  -moz-border-radius: 4px;
+  border-top-style: none;
+  -moz-border-radius-bottomleft: 4px;
+  -moz-border-radius-bottomright: 4px;
   -moz-box-shadow: 0 0 5px rgba(255,255,255,.5) inset;
   color: white;
   text-shadow: 0 0 2px #333;
   font-weight: bold;
-  padding: .2em 2em;
+  padding: .1em 1.5em;
+  margin: 0;
 }
 
 #appmenu-button:hover:not(:active):not([open]) {
   background-color: rgb(248,140,34);
 }
 
 #appmenu-button:hover:active,
 #appmenu-button[open] {
@@ -155,16 +158,41 @@ statusbarpanel#statusbar-display {
   margin: 0;
   -moz-margin-start: .5em;
 }
 
 #appmenu-button > menupopup > menuitem {
   -moz-padding-end: 16px;
 }
 
+.split-menuitem-item[_moz-menuactive="true"],
+.split-menuitem-menu[_moz-menuactive="true"] {
+  background-color: -moz-menuhover;
+  color: -moz-menuhovertext;
+}
+
+/* XXX: stop-gap until the button can be drawn in the title bar */
+%ifdef WINSTRIPE_AERO
+@media not all and (-moz-windows-compositor) {
+%endif
+  #main-window[tabsontop="true"] > #appmenu-button-container > #appmenu-button {
+    position: relative !important;
+    margin-bottom: -1.6em !important;
+  }
+  #navigator-toolbox[tabsontop="true"] > #toolbar-menubar[autohide="true"] {
+    position: relative !important;
+    background-color: -moz-dialog !important;
+  }
+  #navigator-toolbox[tabsontop="true"] > #toolbar-menubar[autohide="true"] ~ #TabsToolbar {
+    -moz-padding-start: 10em !important;
+  }
+%ifdef WINSTRIPE_AERO
+}
+%endif
+
 /* ::::: bookmark buttons ::::: */
 
 toolbarbutton.bookmark-item {
   margin: 0;
   padding: 2px 3px;
 }
 
 toolbarbutton.bookmark-item:hover:active:not([disabled="true"]),
@@ -343,17 +371,17 @@ toolbar[iconsize="small"][mode="icons"] 
 
 .toolbarbutton-menubutton-button[disabled="true"] > .toolbarbutton-icon,
 .toolbarbutton-1[disabled="true"] > .toolbarbutton-icon {
   opacity: .5;
 }
 
 .toolbarbutton-menubutton-button:not([disabled="true"]):not(:active):hover,
 toolbarbutton[type="menu-button"]:not([open="true"]):not(:active):hover > .toolbarbutton-menubutton-dropmarker:not([disabled="true"]),
-.toolbarbutton-1:not([disabled="true"]):not([checked="true"]):not(:active):hover {
+.toolbarbutton-1:not([disabled="true"]):not([checked="true"]):not([open="true"]):not(:active):hover {
   background-color: hsla(190,60%,70%,.5);
   border-color: hsla(190,50%,65%,.8) hsla(190,50%,50%,.8) hsla(190,50%,40%,.8);
   -moz-box-shadow: 0 0 0 1px rgba(255,255,255,.3) inset,
                    0 0 0 2px rgba(255,255,255,.1) inset,
                    0 1px 0 rgba(0,0,0,.1),
                    0 0 5px hsl(190,90%,80%);
   -moz-transition: background-color .4s ease-in,
                    border-color .3s ease-in,
@@ -578,17 +606,17 @@ toolbar:not([iconsize="small"])[mode="ic
 #bookmarks-menu-button {
   -moz-image-region: rect(0, 144px, 18px, 126px);
 }
 
 #bookmarks-menu-button.bookmark-item {
   list-style-image: url("chrome://browser/skin/Toolbar.png");
 }
 
-toolbar[mode="icons"] #bookmarks-menu-button.toolbarbutton-1 {
+#bookmarks-menu-button.toolbarbutton-1 {
   -moz-box-orient: horizontal;
 }
 
 /* print button */
 
 #print-button {
   -moz-image-region: rect(0, 162px, 18px, 144px);
 }
--- a/build/Makefile.in
+++ b/build/Makefile.in
@@ -106,16 +106,19 @@ libs:: bloaturls.txt
 	$(INSTALL) $< $(DIST)/bin
 
 # Install bloatcycle.html into dist/bin/res, for auto-cycling
 # of bloaturls.txt.  This is for browsers that can't do -f
 # autocycling of URLs.
 libs:: bloatcycle.html
 	$(INSTALL) $< $(DIST)/bin/res
 
+libs:: $(topsrcdir)/tools/rb/fix_stack_using_bpsyms.py
+	$(INSTALL) $< $(DIST)/bin
+
 ifeq ($(OS_ARCH),Darwin)
 libs:: $(topsrcdir)/tools/rb/fix-macosx-stack.pl
 	$(INSTALL) $< $(DIST)/bin
 libs:: $(topsrcdir)/tools/rb/fix_macosx_stack.py
 	$(INSTALL) $< $(DIST)/bin
 
 # Basic unit tests for some stuff in the unify script
 check::
--- a/build/automation.py.in
+++ b/build/automation.py.in
@@ -578,17 +578,17 @@ user_pref("camino.use_system_proxy_setti
 
     def isPidAlive(self, pid):
       STILL_ACTIVE = 259
       PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
       pHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
       if not pHandle:
         return False
       pExitCode = ctypes.wintypes.DWORD()
-      ctypes.windll.kernel32.GetExitCodeProcess(pHandle, self.ctypes.byref(pExitCode))
+      ctypes.windll.kernel32.GetExitCodeProcess(pHandle, ctypes.byref(pExitCode))
       ctypes.windll.kernel32.CloseHandle(pHandle)
       if (pExitCode.value == STILL_ACTIVE):
         return True
       else:
         return False
 
     def killPid(self, pid):
       PROCESS_TERMINATE = 0x0001
@@ -644,45 +644,54 @@ user_pref("camino.use_system_proxy_setti
         # We should have a "crashinject" program in our utility path
         crashinject = os.path.normpath(os.path.join(utilityPath, "crashinject.exe"))
         if os.path.exists(crashinject) and subprocess.Popen([crashinject, str(proc.pid)]).wait() == 0:
           return
       #TODO: kill the process such that it triggers Breakpad on OS X (bug 525296)
     self.log.info("Can't trigger Breakpad, just killing process")
     proc.kill()
 
-  def waitForFinish(self, proc, utilityPath, timeout, maxTime, startTime, debuggerInfo):
+  def waitForFinish(self, proc, utilityPath, timeout, maxTime, startTime, debuggerInfo, symbolsPath):
     """ Look for timeout or crashes and return the status after the process terminates """
     stackFixerProcess = None
-    stackFixerModule = None
+    stackFixerFunction = None
     didTimeout = False
     if proc.stdout is None:
       self.log.info("TEST-INFO: Not logging stdout or stderr due to debugger connection")
     else:
       logsource = proc.stdout
-      if self.IS_DEBUG_BUILD and self.IS_LINUX:
-        # Run logsource through fix-linux-stack.pl
+
+      if self.IS_DEBUG_BUILD and (self.IS_MAC or self.IS_LINUX) and symbolsPath and os.path.exists(symbolsPath):
+        # Run each line through a function in fix_stack_using_bpsyms.py (uses breakpad symbol files)
+        # This method is preferred for Tinderbox builds, since native symbols may have been stripped.
+        sys.path.insert(0, utilityPath)
+        import fix_stack_using_bpsyms as stackFixerModule
+        stackFixerFunction = lambda line: stackFixerModule.fixSymbols(line, symbolsPath)
+        del sys.path[0]
+      elif self.IS_DEBUG_BUILD and self.IS_MAC and False:
+        # Run each line through a function in fix_macosx_stack.py (uses atos)
+        sys.path.insert(0, utilityPath)
+        import fix_macosx_stack as stackFixerModule
+        stackFixerFunction = lambda line: stackFixerModule.fixSymbols(line)
+        del sys.path[0]
+      elif self.IS_DEBUG_BUILD and self.IS_LINUX:
+        # Run logsource through fix-linux-stack.pl (uses addr2line)
+        # This method is preferred for developer machines, so we don't have to run "make buildsymbols".
         stackFixerProcess = self.Process([self.PERL, os.path.join(utilityPath, "fix-linux-stack.pl")],
                                          stdin=logsource,
                                          stdout=subprocess.PIPE)
         logsource = stackFixerProcess.stdout
 
-      if self.IS_DEBUG_BUILD and self.IS_MAC and False:
-        # Import fix_macosx_stack.py from utilityPath
-        sys.path.insert(0, utilityPath)
-        import fix_macosx_stack as stackFixerModule
-        del sys.path[0]
-
       (line, didTimeout) = self.readWithTimeout(logsource, timeout)
       hitMaxTime = False
       while line != "" and not didTimeout:
         if "TEST-START" in line and "|" in line:
           self.lastTestSeen = line.split("|")[1].strip()
-        if stackFixerModule:
-          line = stackFixerModule.fixSymbols(line)
+        if stackFixerFunction:
+          line = stackFixerFunction(line)
         self.log.info(line.rstrip())
         (line, didTimeout) = self.readWithTimeout(logsource, timeout)
         if not hitMaxTime and maxTime and datetime.now() - startTime > timedelta(seconds = maxTime):
           # Kill the application, but continue reading from stack fixer so as not to deadlock on stackFixerProcess.wait().
           hitMaxTime = True
           self.log.info("TEST-UNEXPECTED-FAIL | %s | application ran for longer than allowed maximum time of %d seconds", self.lastTestSeen, int(maxTime))
           self.killAndGetStack(proc, utilityPath, debuggerInfo)
       if didTimeout:
@@ -809,17 +818,17 @@ user_pref("camino.use_system_proxy_setti
     self.lastTestSeen = "automation.py"
     proc = self.Process([cmd] + args,
                  env = self.environment(env, xrePath = xrePath,
                                    crashreporter = not debuggerInfo),
                  stdout = outputPipe,
                  stderr = subprocess.STDOUT)
     self.log.info("INFO | automation.py | Application pid: %d", proc.pid)
 
-    status = self.waitForFinish(proc, utilityPath, timeout, maxTime, startTime, debuggerInfo)
+    status = self.waitForFinish(proc, utilityPath, timeout, maxTime, startTime, debuggerInfo, symbolsPath)
     self.log.info("INFO | automation.py | Application ran for: %s", str(datetime.now() - startTime))
 
     # Do a final check for zombie child processes.
     self.checkForZombies(processLog)
     automationutils.checkForCrashes(os.path.join(profileDir, "minidumps"), symbolsPath, self.lastTestSeen)
 
     if os.path.exists(processLog):
       os.unlink(processLog)
--- a/build/mobile/remoteautomation.py
+++ b/build/mobile/remoteautomation.py
@@ -61,17 +61,17 @@ class RemoteAutomation(Automation):
         self._appName = appName
 
     def setRemoteProfile(self, remoteProfile):
         self._remoteProfile = remoteProfile
 
     def setProduct(self, product):
         self._product = product
 
-    def waitForFinish(self, proc, utilityPath, timeout, maxTime, startTime, debuggerInfo):
+    def waitForFinish(self, proc, utilityPath, timeout, maxTime, startTime, debuggerInfo, symbolsDir):
         # maxTime is used to override the default timeout, we should honor that
         status = proc.wait(timeout = maxTime)
 
         print proc.stdout
 
         if (status == 1 and self._devicemanager.processExist(proc.procName)):
             # Then we timed out, make sure Fennec is dead
             proc.kill()
--- a/build/wince/shunt/environment.cpp
+++ b/build/wince/shunt/environment.cpp
@@ -154,18 +154,18 @@ getenv(const char* name)
   if (entry && entry->value[0] != 0) {
     return entry->value;
   }
 
   return NULL;
 }
 
 char
-GetEnvironmentVariableW(const unsigned short* lpName,
-                        unsigned short* lpBuffer,
+GetEnvironmentVariableW(const WCHAR* lpName,
+                        WCHAR* lpBuffer,
                         unsigned long nSize)
 {
   char key[256];
   int rv = WideCharToMultiByte(CP_ACP, 0, lpName, -1, key, 255, NULL, NULL);
   if (rv <= 0)
     return 0;
 
   key[rv] = 0;
@@ -175,18 +175,18 @@ GetEnvironmentVariableW(const unsigned s
   if (!val)
     return 0;
 
   // strlen(val)+1, let MBTWC convert the nul byte for us
   return MultiByteToWideChar(CP_ACP, 0, val, strlen(val)+1, lpBuffer, nSize);
 }
 
 char
-SetEnvironmentVariableW(const unsigned short* name,
-                        const unsigned short* value)
+SetEnvironmentVariableW(const WCHAR* name,
+                        const WCHAR* value)
 {
   char key[256];
   char val[256];
   int rv;
 
   rv = WideCharToMultiByte(CP_ACP, 0, name, -1, key, 255, NULL, NULL);
   if (rv < 0)
     return rv;
@@ -199,41 +199,41 @@ SetEnvironmentVariableW(const unsigned s
 
   val[rv] = 0;
 
   putenv_copy(key, val);
   return 0;
 }
 
 
-unsigned int ExpandEnvironmentStringsW(const unsigned short* lpSrc,
-                                       unsigned short* lpDst,
+unsigned int ExpandEnvironmentStringsW(const WCHAR* lpSrc,
+                                       WCHAR* lpDst,
                                        unsigned int nSize)
 {
   if ( NULL == lpDst )
     return 0;
 
   unsigned int size = 0;
   unsigned int index = 0;
   unsigned int origLen = wcslen(lpSrc);
 
-  const unsigned short *pIn = lpSrc;
-  unsigned short *pOut = lpDst;
+  const WCHAR *pIn = lpSrc;
+  WCHAR *pOut = lpDst;
 
   while ( index < origLen ) {
 
     if (*pIn != L'%') {  // Regular char, copy over
       if ( size++ < nSize ) *pOut = *pIn, pOut++;
       index++, pIn++;
       continue;
     }
 
     // Have a starting '%' - look for matching '%'
     int envlen = 0;
-    const unsigned short *pTmp = pIn + 1;
+    const WCHAR *pTmp = pIn + 1;
     while ( *pTmp != L'%' && *pTmp != L' ' ) {
       envlen++, pTmp++;
       if ( origLen < index + envlen ) {    // Ran past end of original
         while ( envlen-- ) {
           if ( size++ < nSize ) *pOut = *pIn, pOut++;
           index++, pIn++;
         }
         break;
@@ -269,17 +269,17 @@ unsigned int ExpandEnvironmentStringsW(c
       pIn = ++pTmp;
     }
   }
 
   if ( size < nSize ) lpDst[size] = 0;
   return size;
 }
 
-unsigned short *
+WCHAR *
 mozce_GetEnvironmentCL()
 {
   env_entry *entry = env_head;
   int len = 0;
   while (entry) {
     if (entry->flag == ENV_IS_STATIC) {
       entry = entry->next;
       continue;
--- a/build/wince/shunt/include/environment.h
+++ b/build/wince/shunt/include/environment.h
@@ -42,22 +42,22 @@
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 /* Environment stuff */
 char* getenv(const char* inName);
 int putenv(const char *a);
-char SetEnvironmentVariableW(const unsigned short * name, const unsigned short * value );
-char GetEnvironmentVariableW(const unsigned short * lpName, unsigned short* lpBuffer, unsigned long nSize);
+char SetEnvironmentVariableW(const wchar_t * name, const wchar_t * value );
+char GetEnvironmentVariableW(const wchar_t * lpName, wchar_t* lpBuffer, unsigned long nSize);
 
-unsigned int ExpandEnvironmentStringsW(const unsigned short* lpSrc,
-				       unsigned short* lpDst,
+unsigned int ExpandEnvironmentStringsW(const wchar_t* lpSrc,
+				       wchar_t* lpDst,
 				       unsigned int nSize);
 
-unsigned short* mozce_GetEnvironmentCL();
+wchar_t* mozce_GetEnvironmentCL();
 
 #ifdef __cplusplus
 };
 #endif
 
 #endif //MOZCE_ENVIRONMENT_H
--- a/build/wince/shunt/include/mozce_shunt.h
+++ b/build/wince/shunt/include/mozce_shunt.h
@@ -33,31 +33,31 @@
  * 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 MOZCE_SHUNT_H
 #define MOZCE_SHUNT_H
 
-#include "environment.h"
-
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 #ifndef _WCHAR_T_DEFINED
 typedef unsigned short wchar_t;
 #define _WCHAR_T_DEFINED
 #endif
 
 #ifdef __cplusplus
 }   //extern "C" 
 #endif
 
+#include "environment.h"
+
 #ifdef MOZ_MEMORY
 
 #ifdef __cplusplus
 
 // define these so we don't include <new> from either VC or
 // the CE5 SDK
 #define _NEW_
 #define _INC_NEW
@@ -177,28 +177,28 @@ extern int errno;
 char* strerror(int);
 
 /* abort */
 void abort(void);
   
 /* Environment stuff */
 char* getenv(const char* inName);
 int putenv(const char *a);
-char SetEnvironmentVariableW(const unsigned short * name, const unsigned short * value );
-char GetEnvironmentVariableW(const unsigned short * lpName, unsigned short* lpBuffer, unsigned long nSize);
+char SetEnvironmentVariableW(const wchar_t * name, const wchar_t * value );
+char GetEnvironmentVariableW(const wchar_t * lpName, wchar_t* lpBuffer, unsigned long nSize);
   
-unsigned int ExpandEnvironmentStringsW(const unsigned short* lpSrc,
-				       unsigned short* lpDst,
+unsigned int ExpandEnvironmentStringsW(const wchar_t* lpSrc,
+				       wchar_t* lpDst,
 				       unsigned int nSize);
 
 /* File system stuff */
-unsigned short * _wgetcwd(unsigned short* dir, unsigned long size);
-unsigned short *_wfullpath( unsigned short *absPath, const unsigned short *relPath, unsigned long maxLength );
+wchar_t * _wgetcwd(wchar_t* dir, unsigned long size);
+wchar_t *_wfullpath(wchar_t *absPath, const wchar_t *relPath, unsigned long maxLength );
 int _unlink(const char *filename );
-int _wchdir(const unsigned short* path);
+int _wchdir(const wchar_t* path);
   
 /* The time stuff should be defined here, but it can't be because it
    is already defined in time.h.
   
  size_t strftime(char *, size_t, const char *, const struct tm *)
  struct tm* localtime(const time_t* inTimeT)
  struct tm* mozce_gmtime_r(const time_t* inTimeT, struct tm* outRetval)
  struct tm* gmtime(const time_t* inTimeT)
@@ -223,17 +223,17 @@ struct tm* localtime_r(const time_t* inT
 /* The locale stuff should be defined here, but it can't be because it
    is already defined in locale.h.
   
  struct lconv * localeconv(void)
   
 */
 
 
-unsigned short* mozce_GetEnvironmentCL();
+wchar_t* mozce_GetEnvironmentCL();
 
   /* square root of 1/2, missing from math.h */ 
 #define M_SQRT1_2  0.707106781186547524401
 
 #ifdef __cplusplus
 };
 #endif
 
--- a/build/wince/shunt/shunt.cpp
+++ b/build/wince/shunt/shunt.cpp
@@ -108,33 +108,33 @@ char* strerror(int inErrno)
 
 int errno = 0;
 
 
 ////////////////////////////////////////////////////////
 //  File System Stuff
 ////////////////////////////////////////////////////////
 
-unsigned short * _wgetcwd(unsigned short * dir, unsigned long size)
+wchar_t * _wgetcwd(wchar_t * dir, unsigned long size)
 {
-  unsigned short tmp[MAX_PATH] = {0};
+  wchar_t tmp[MAX_PATH] = {0};
   GetEnvironmentVariableW(L"CWD", tmp, size);
   if (tmp && tmp[0]) {
     if (wcslen(tmp) > size)
       return 0;
     if (!dir) {
-      dir = (unsigned short*)malloc(sizeof(unsigned short) * (wcslen(tmp) + 2));
+      dir = (wchar_t*)malloc(sizeof(wchar_t) * (wcslen(tmp) + 2));
       if (!dir)
         return 0;
     }
     wcscpy(dir, tmp);
   } else {
     unsigned long i;
     if (!dir) {
-      dir = (unsigned short*)malloc(sizeof(unsigned short) * (MAX_PATH + 1));
+      dir = (wchar_t*)malloc(sizeof(wchar_t) * (MAX_PATH + 1));
       if (!dir)
         return 0;
     }
     if (!GetModuleFileNameW(GetModuleHandle (NULL), dir, MAX_PATH))
       return 0;
     for (i = wcslen(dir); i && dir[i] != '\\'; i--) {}
     dir[i + 1] = '\0';
     SetEnvironmentVariableW(L"CWD", dir);
@@ -142,22 +142,22 @@ unsigned short * _wgetcwd(unsigned short
   size_t len = wcslen(dir);
   if (dir[len - 1] != '\\' && (len + 2) < size) {
     dir[len] = '\\';
     dir[len + 1] = '\0';
   }
   return dir;
 }
 
-unsigned short *_wfullpath( unsigned short *absPath, const unsigned short *relPath, unsigned long maxLength )
+wchar_t *_wfullpath( wchar_t *absPath, const wchar_t *relPath, unsigned long maxLength )
 {
   if(absPath == NULL){
-    absPath = (unsigned short *)malloc(maxLength*sizeof(unsigned short));
+    absPath = (wchar_t *)malloc(maxLength*sizeof(wchar_t));
   }
-  unsigned short cwd[MAX_PATH];
+  wchar_t cwd[MAX_PATH];
   if (NULL == _wgetcwd( cwd, MAX_PATH))
     return NULL;
 
   unsigned long len = wcslen(cwd);
   if(!(cwd[len-1] == TCHAR('/') || cwd[len-1] == TCHAR('\\'))&& len< maxLength){
     cwd[len] = TCHAR('\\');
     cwd[++len] = TCHAR('\0');
   }
@@ -176,17 +176,17 @@ unsigned short *_wfullpath( unsigned sho
 }
 
 int _wchdir(const WCHAR* path) {
   return SetEnvironmentVariableW(L"CWD", path);
 }
 
 int _unlink(const char *filename)
 {
-  unsigned short wname[MAX_PATH];
+  wchar_t wname[MAX_PATH];
   
   MultiByteToWideChar(CP_ACP,
                       0,
                       filename,
                       strlen(filename)+1,
                       wname,
                       MAX_PATH );
   return DeleteFileW(wname)?0:-1;
--- a/chrome/src/nsChromeRegistry.cpp
+++ b/chrome/src/nsChromeRegistry.cpp
@@ -468,17 +468,17 @@ nsresult nsChromeRegistry::RefreshWindow
   if (!domDocument)
     return NS_OK;
 
   nsCOMPtr<nsIDocument> document = do_QueryInterface(domDocument);
   if (!document)
     return NS_OK;
 
   // Deal with the agent sheets first.  Have to do all the style sets by hand.
-  nsCOMPtr<nsIPresShell> shell = document->GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> shell = document->GetShell();
   if (shell) {
     // Reload only the chrome URL agent style sheets.
     nsCOMArray<nsIStyleSheet> agentSheets;
     rv = shell->GetAgentStyleSheets(agentSheets);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMArray<nsIStyleSheet> newAgentSheets;
     for (PRInt32 l = 0; l < agentSheets.Count(); ++l) {
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -125,17 +125,16 @@ ENABLE_TESTS	= @ENABLE_TESTS@
 IBMBIDI = @IBMBIDI@
 MOZ_UNIVERSALCHARDET = @MOZ_UNIVERSALCHARDET@
 ACCESSIBILITY = @ACCESSIBILITY@
 MOZ_VIEW_SOURCE = @MOZ_VIEW_SOURCE@
 MOZ_JSLOADER  = @MOZ_JSLOADER@
 MOZ_USE_NATIVE_UCONV = @MOZ_USE_NATIVE_UCONV@
 MOZ_BRANDING_DIRECTORY = @MOZ_BRANDING_DIRECTORY@
 XPCOM_USE_LEA = @XPCOM_USE_LEA@
-MOZ_ENABLE_POSTSCRIPT = @MOZ_ENABLE_POSTSCRIPT@
 MOZ_INSTALLER	= @MOZ_INSTALLER@
 MOZ_UPDATER	= @MOZ_UPDATER@
 MOZ_UPDATE_CHANNEL	= @MOZ_UPDATE_CHANNEL@
 MOZ_UPDATE_PACKAGING	= @MOZ_UPDATE_PACKAGING@
 MOZ_NO_ACTIVEX_SUPPORT = @MOZ_NO_ACTIVEX_SUPPORT@
 MOZ_ACTIVEX_SCRIPTING_SUPPORT = @MOZ_ACTIVEX_SCRIPTING_SUPPORT@
 MOZ_DISABLE_PARENTAL_CONTROLS = @MOZ_DISABLE_PARENTAL_CONTROLS@
 XPC_IDISPATCH_SUPPORT = @XPC_IDISPATCH_SUPPORT@
--- a/config/config.mk
+++ b/config/config.mk
@@ -498,16 +498,23 @@ endif # CROSS_COMPILE
 # NOTE: First, we clear FAIL_ON_WARNINGS[_DEBUG] if we're doing a Windows PGO
 # build, since WARNINGS_AS_ERRORS has been suspected of causing isuses in that
 # situation. (See bug 437002.)
 ifeq (WINNT_1,$(OS_ARCH)_$(MOZ_PROFILE_GENERATE)$(MOZ_PROFILE_USE))
 FAIL_ON_WARNINGS_DEBUG=
 FAIL_ON_WARNINGS=
 endif # WINNT && (MOS_PROFILE_GENERATE ^ MOZ_PROFILE_USE)
 
+# Also clear FAIL_ON_WARNINGS[_DEBUG] for Android builds, since
+# they have some platform-specific warnings we haven't fixed yet.
+ifeq ($(OS_TARGET),Android)
+FAIL_ON_WARNINGS_DEBUG=
+FAIL_ON_WARNINGS=
+endif # Android
+
 # Now, check for debug version of flag; it turns on normal flag in debug builds.
 ifdef FAIL_ON_WARNINGS_DEBUG
 ifdef MOZ_DEBUG
 FAIL_ON_WARNINGS = 1
 endif # MOZ_DEBUG
 endif # FAIL_ON_WARNINGS_DEBUG
 
 # Check for normal version of flag, and add WARNINGS_AS_ERRORS if it's set to 1.
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -350,17 +350,16 @@ endif
 endif # !GNU_CC
 
 ifdef ENABLE_CXX_EXCEPTIONS
 CXXFLAGS += $(MOZ_EXCEPTIONS_FLAGS_ON) -DMOZ_CPP_EXCEPTIONS=1
 endif # ENABLE_CXX_EXCEPTIONS
 endif # WINNT
 
 ifeq ($(SOLARIS_SUNPRO_CXX),1)
-CXXFLAGS += -features=extensions -D__FUNCTION__=__func__
 ifeq (86,$(findstring 86,$(OS_TEST)))
 OS_LDFLAGS += -M $(topsrcdir)/config/solaris_ia32.map
 endif # x86
 endif # Solaris Sun Studio C++
 
 ifeq (,$(filter-out WINNT WINCE,$(HOST_OS_ARCH)))
 HOST_PDBFILE=$(basename $(@F)).pdb
 endif
--- a/configure.in
+++ b/configure.in
@@ -661,24 +661,22 @@ case "$target" in
             elif test $_CC_BUILD -ge 762; then
                _USE_DYNAMICBASE=1
             fi
             AC_DEFINE(_CRT_SECURE_NO_DEPRECATE)
             AC_DEFINE(_CRT_NONSTDC_NO_DEPRECATE)
         elif test "$_CC_MAJOR_VERSION" = "15"; then
             _CC_SUITE=9
             CXXFLAGS="$CXXFLAGS -Zc:wchar_t-"
-            LDFLAGS="$LDFLAGS -MANIFESTUAC:NO"
             _USE_DYNAMICBASE=1
             AC_DEFINE(_CRT_SECURE_NO_WARNINGS)
             AC_DEFINE(_CRT_NONSTDC_NO_WARNINGS)
         elif test "$_CC_MAJOR_VERSION" = "16"; then
             _CC_SUITE=10
             CXXFLAGS="$CXXFLAGS -Zc:wchar_t-"
-            LDFLAGS="$LDFLAGS -MANIFESTUAC:NO"
             _USE_DYNAMICBASE=1
             AC_DEFINE(_CRT_SECURE_NO_WARNINGS)
             AC_DEFINE(_CRT_NONSTDC_NO_WARNINGS)
         else
             AC_MSG_ERROR([This version of the MSVC compiler, $CC_VERSION , is unsupported.])
         fi
 
         _MOZ_RTTI_FLAGS_ON='-GR'
@@ -1229,18 +1227,16 @@ XPCOM_STANDALONE_GLUE_LDOPTS='$(LIBXUL_D
 MOZ_FS_LAYOUT=unix
 
 MOZ_COMPONENT_NSPR_LIBS='-L$(LIBXUL_DIST)/bin $(NSPR_LIBS)'
 
 USE_DEPENDENT_LIBS=1
 
 _PLATFORM_DEFAULT_TOOLKIT=cairo-gtk2
 
-MOZ_ENABLE_POSTSCRIPT=1 
-
 if test -n "$CROSS_COMPILE"; then
     OS_TARGET="${target_os}"
     OS_ARCH=`echo $target_os | sed -e 's|/|_|g'`
     OS_RELEASE=
     case "${target_os}" in
         linux*)       OS_ARCH=Linux OS_TARGET=Linux ;;
         kfreebsd*-gnu) OS_ARCH=GNU_kFreeBSD OS_TARGET=GNU_kFreeBSD ;;
         gnu*)         OS_ARCH=GNU ;;
@@ -1599,25 +1595,16 @@ if test "$GNU_CC"; then
 
     if test -z "$INTEL_CC"; then
       _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -W"
     fi
 
     _DEFINES_CFLAGS='-include $(DEPTH)/mozilla-config.h -DMOZILLA_CLIENT'
     _USE_CPP_INCLUDE_FLAG=1
 elif test "$SOLARIS_SUNPRO_CC"; then
-    MKSHLIB='$(LD) $(DSO_LDOPTS) -h $@ -o $@'
-    MKCSHLIB='$(LD) $(DSO_LDOPTS) -h $@ -o $@'
-
-    DSO_LDOPTS='-shared'
-    if test "$GNU_LD"; then
-        # Don't allow undefined symbols in libraries
-        DSO_LDOPTS="$DSO_LDOPTS -z defs"
-    fi
-
     DSO_CFLAGS=''
     if test "$CPU_ARCH" = "sparc"; then
         # for Sun Studio on Solaris/SPARC
         DSO_PIC_CFLAGS='-xcode=pic32'
     else
         DSO_PIC_CFLAGS='-KPIC'
     fi
     _DEFINES_CFLAGS='$(ACDEFINES) -D_MOZILLA_CONFIG_H_ -DMOZILLA_CLIENT'
@@ -2036,17 +2023,16 @@ case "$target" in
     MOZ_OPTIMIZE_FLAGS="-O3"
     _PEDANTIC=
     CFLAGS="$CFLAGS -fpascal-strings -fno-common"
     CXXFLAGS="$CXXFLAGS -fpascal-strings -fno-common"
     DLL_SUFFIX=".dylib"
     DSO_LDOPTS=''
     STRIP="$STRIP -x -S"
     _PLATFORM_DEFAULT_TOOLKIT='cairo-cocoa'
-    MOZ_ENABLE_POSTSCRIPT=
     TARGET_NSPR_MDCPUCFG='\"md/_darwin.cfg\"'
     # The ExceptionHandling framework is needed for Objective-C exception
     # logging code in nsObjCExceptions.h. Currently we only use that in debug
     # builds.
     MOZ_DEBUG_LDFLAGS="$MOZ_DEBUG_LDFLAGS -framework ExceptionHandling"
 
     dnl DTrace and -dead_strip don't interact well. See bug 403132.
     dnl ===================================================================
@@ -2303,17 +2289,16 @@ ia64*-hpux*)
     AC_DEFINE(STDC_HEADERS)
     AC_DEFINE(NEW_H, <new>)
     AC_DEFINE(WIN32_LEAN_AND_MEAN)
     AC_DEFINE(HAVE_LOCALTIME_R)
 
     TARGET_MD_ARCH=win32
     _PLATFORM_DEFAULT_TOOLKIT='cairo-windows'
     BIN_SUFFIX='.exe'
-    MOZ_ENABLE_POSTSCRIPT=
     MOZ_USER_DIR="Mozilla"
 
     MOZ_GFX_OPTIMIZE_MOBILE=1
 
     # Sanity check for WINCE_WINDOWS_MOBILE
     # XXX disabled until we can fix the mobile tinderbox
     ##if test "$WINCE_WINDOWS_MOBILE"; then
     ##   AC_CHECK_HEADER(tpcshell.h, [],
@@ -2426,17 +2411,16 @@ ia64*-hpux*)
     AC_DEFINE(XP_WIN32)
     AC_DEFINE(HW_THREADS)
     AC_DEFINE(STDC_HEADERS)
     AC_DEFINE(NEW_H, <new>)
     AC_DEFINE(WIN32_LEAN_AND_MEAN)
     TARGET_MD_ARCH=win32
     _PLATFORM_DEFAULT_TOOLKIT='cairo-windows'
     BIN_SUFFIX='.exe'
-    MOZ_ENABLE_POSTSCRIPT=
     MOZ_USER_DIR="Mozilla"
 
     dnl Hardcode to win95 for now - cls
     TARGET_NSPR_MDCPUCFG='\"md/_win95.cfg\"'
 
     dnl set NO_X11 defines here as the general check is skipped on win32
     no_x=yes
     AC_DEFINE(NO_X11)
@@ -2630,17 +2614,16 @@ ia64*-hpux*)
     WARNINGS_AS_ERRORS='-Werror'
     MOZ_DEBUG_FLAGS="-g -fno-inline"
     MOZ_OPTIMIZE_FLAGS="-O2"
     MOZ_OPTIMIZE_LDFLAGS="-s -Zlinker /EXEPACK:2 -Zlinker /PACKCODE -Zlinker /PACKDATA"
     DYNAMIC_XPCOM_LIBS='-L$(LIBXUL_DIST)/lib $(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xpcom_core.lib $(LIBXUL_DIST)/lib/mozalloc.lib'
     LIBXUL_LIBS='-L$(LIBXUL_DIST)/lib $(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xul.lib $(LIBXUL_DIST)/lib/mozalloc.lib'
     TARGET_MD_ARCH=os2
     _PLATFORM_DEFAULT_TOOLKIT="cairo-os2"
-    MOZ_ENABLE_POSTSCRIPT=
     RC=rc.exe
     RCFLAGS='-n'
     MOZ_USER_DIR="Mozilla"
 
     if test "$MOZTOOLS"; then
         MOZ_TOOLS_DIR=`echo $MOZTOOLS | sed -e 's|\\\\|/|g'`
     else
         AC_MSG_ERROR([MOZTOOLS is not set])
@@ -2717,44 +2700,44 @@ alpha*-*-osf*)
        DSO_LDOPTS='-G'
     fi
     ;;
 
 *-solaris*) 
     AC_DEFINE(SOLARIS)
     TARGET_NSPR_MDCPUCFG='\"md/_solaris.cfg\"'
     SYSTEM_MAKEDEPEND=
+    MOZ_FIX_LINK_PATHS=
     # $ORIGIN/.. is for shared libraries under components/ to locate shared
     # libraries one level up (e.g. libnspr4.so)
-    LDFLAGS="$LDFLAGS -z ignore -R '\$\$ORIGIN:\$\$ORIGIN/..'"
     if test "$SOLARIS_SUNPRO_CC"; then
-       LIBS="-lCrun -lCstd $LIBS"
+       LDFLAGS="$LDFLAGS -z ignore -R '\$\$ORIGIN:\$\$ORIGIN/..' -z lazyload -z combreloc -z muldefs"
+       LIBS="-lCrun -lCstd -lc $LIBS"
        NS_USE_NATIVE=1
-       MOZ_FIX_LINK_PATHS=
        AC_DEFINE(NSCAP_DISABLE_DEBUG_PTR_TYPES)
-       CFLAGS="$CFLAGS -xlibmieee -xstrconst -xbuiltin=%all"
-       CXXFLAGS="$CXXFLAGS -xlibmieee -xbuiltin=%all -features=tmplife,tmplrefstatic -norunpath"
+       CFLAGS="$CFLAGS -xlibmieee -xstrconst -xbuiltin=%all -D__FUNCTION__=__func__"
+       CXXFLAGS="$CXXFLAGS -xlibmieee -xbuiltin=%all -features=tmplife,tmplrefstatic,extensions -norunpath -D__FUNCTION__=__func__"
        _MOZ_EXCEPTIONS_FLAGS_ON='-features=except'
        _MOZ_EXCEPTIONS_FLAGS_OFF='-features=no%except'
-       LDFLAGS="-xildoff -z lazyload -z combreloc $LDFLAGS"
+       LDFLAGS="-xildoff $LDFLAGS"
        if test -z "$CROSS_COMPILE" && test -f /usr/lib/ld/map.noexstk; then
            _SAVE_LDFLAGS=$LDFLAGS
            LDFLAGS="-M /usr/lib/ld/map.noexstk $LDFLAGS" 
            AC_TRY_LINK([#include <stdio.h>],
                        [printf("Hello World\n");],
                        ,
                        [LDFLAGS=$_SAVE_LDFLAGS])
        fi
        WARNINGS_AS_ERRORS='-Werror'
        MOZ_OPTIMIZE_FLAGS="-xO4"
        MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_PIC_FLAGS) $(DSO_LDOPTS) -h $@ -o $@'
-       MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_FLAGS) -G -z muldefs -h $@ -o $@'
+       MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_FLAGS) $(DSO_LDOPTS) -h $@ -o $@'
        MKSHLIB_FORCE_ALL='-z allextract'
        MKSHLIB_UNFORCE_ALL='-z defaultextract'
-       DSO_LDOPTS='-G -z muldefs'
+       DSO_LDOPTS='-G'
        AR_LIST="$AR t"
        AR_EXTRACT="$AR x"
        AR_DELETE="$AR d"
        AR='$(CXX) -xar'
        AR_FLAGS='-o $@'
        AS='/usr/ccs/bin/as'
        ASFLAGS="$ASFLAGS -K PIC -L -P -D_ASM -D__STDC__=0"
        AS_DASH_C_FLAG=''
@@ -2764,35 +2747,48 @@ alpha*-*-osf*)
        AC_MSG_CHECKING([for Sun C++ compiler version >= 5.9])
        AC_LANG_SAVE
        AC_LANG_CPLUSPLUS
        AC_TRY_COMPILE([],
            [#if (__SUNPRO_CC < 0x590)
            #error "Denied"
            #endif],
            _BAD_COMPILER=,_BAD_COMPILER=1)
-        if test -n "$_BAD_COMPILER"; then
-            _res="no"
-            AC_MSG_ERROR([Sun C++ 5.9 (Sun Studio 12) or higher is required to build. Your compiler version is $CXX_VERSION .])
-        else
-            _res="yes"
-        fi
-        AC_MSG_RESULT([$_res])
-        AC_LANG_RESTORE
+       if test -n "$_BAD_COMPILER"; then
+           _res="no"
+           AC_MSG_ERROR([Sun C++ 5.9 (Sun Studio 12) or higher is required to build. Your compiler version is $CXX_VERSION .])
+       else
+           _res="yes"
+       fi
+       AC_TRY_COMPILE([],
+           [#if (__SUNPRO_CC >= 0x5100)
+           #error "Sun C++ 5.10 or above"
+           #endif],
+           _ABOVE_SS12U1=,_ABOVE_SS12U1=1)
+       if test "$_ABOVE_SS12U1"; then
+           # disable xannotate
+           CXXFLAGS="$CXXFLAGS -xannotate=no"
+       fi
+       AC_MSG_RESULT([$_res])
+       AC_LANG_RESTORE
     else
+       LDFLAGS="$LDFLAGS -Wl,-z,ignore -Wl,-R,'\$\$ORIGIN:\$\$ORIGIN/..' -Wl,-z,lazyload -Wl,-z,combreloc -Wl,-z,muldefs"
+       LIBS="-lc $LIBS"
+       MKSHLIB_FORCE_ALL='-Wl,-z -Wl,allextract'
+       MKSHLIB_UNFORCE_ALL='-Wl,-z -Wl,defaultextract'
        ASFLAGS="$ASFLAGS -fPIC"
-       DSO_LDOPTS='-G'
+       DSO_LDOPTS='-shared'
        _WARNINGS_CFLAGS=''
        _WARNINGS_CXXFLAGS=''
        if test "$OS_RELEASE" = "5.3"; then
-	  AC_DEFINE(MUST_UNDEF_HAVE_BOOLEAN_AFTER_INCLUDES)
+           AC_DEFINE(MUST_UNDEF_HAVE_BOOLEAN_AFTER_INCLUDES)
        fi
     fi
     if test "$OS_RELEASE" = "5.5.1"; then
-       AC_DEFINE(NEED_USLEEP_PROTOTYPE)
+        AC_DEFINE(NEED_USLEEP_PROTOTYPE)
     fi
     ;;
 
 *-sunos*) 
     DSO_LDOPTS='-Bdynamic'
     MKSHLIB='-$(LD) $(DSO_LDOPTS) -o $@'
     MKCSHLIB='-$(LD) $(DSO_LDOPTS) -o $@'
     AC_DEFINE(SUNOS4)
@@ -5905,17 +5901,17 @@ MOZ_ARG_DISABLE_BOOL(webm,
 if test -n "$MOZ_WEBM"; then
     AC_DEFINE(MOZ_WEBM)
     MOZ_SYDNEYAUDIO=1
     MOZ_MEDIA=1
     MOZ_VORBIS=1
 
     dnl Detect if we can use an assembler to compile optimized assembly for libvpx.
     dnl For Win32 (MSVC) we must use MASM.
-    if test "$OS_ARCH" = "WINNT" -a "$CPU_ARCH" = "x86" -a "$GNU_CC" != "yes"; then
+    if test "$OS_ARCH" = "WINNT" -a "$CPU_ARCH" = "x86" -a -z "$GNU_CC"; then
         AC_MSG_CHECKING([for MASM assembler])
         AC_CHECK_PROGS(VPX_AS, ml, "")
         if test -n "$VPX_AS"; then
           VPX_X86_ASM=1
           VPX_AS='sh $(topsrcdir)/media/libvpx/yasm2masm-as.sh'
         else
             AC_MSG_ERROR([Need MASM (ml.exe) in order to assemble libvpx optimized assembly. Either disable webm (reconfigure with --disable-webm) or install MASM. MASM is included in the Windows 7 SDK, or you can download MASM directly from http://www.microsoft.com/downloads/details.aspx?familyid=7a1c9da0-0510-44a2-b042-7ef370530c64&displaylang=en])
         fi
@@ -5931,27 +5927,37 @@ if test -n "$MOZ_WEBM"; then
         Linux:x86|Linux:i?86)
           VPX_ASFLAGS="-f elf32 -rnasm -pnasm"
           VPX_X86_ASM=1
         ;;
         Linux:x86_64)
           VPX_ASFLAGS="-f elf64 -rnasm -pnasm -DPIC"
           VPX_X86_ASM=1
         ;;
+        SunOS:i?86)
+          VPX_ASFLAGS="-f elf32 -rnasm -pnasm"
+          VPX_X86_ASM=1
+        ;;
+        SunOS:x86_64)
+          VPX_ASFLAGS="-f elf64 -rnasm -pnasm -DPIC"
+          VPX_X86_ASM=1
+        ;;
         Darwin:i?86)
           VPX_ASFLAGS="-f macho32 -rnasm -pnasm -DPIC"
           VPX_X86_ASM=1
         ;;
         Darwin:x86_64)
           VPX_ASFLAGS="-f macho64 -rnasm -pnasm -DPIC"
           VPX_X86_ASM=1
         ;;
         WINNT:x86_64)
-          VPX_ASFLAGS="-f x64 -rnasm -pnasm"
-          VPX_X86_ASM=1
+          if test -z "$GNU_CC"; then
+            VPX_ASFLAGS="-f x64 -rnasm -pnasm"
+            VPX_X86_ASM=1
+          fi
         ;;
         esac
       fi # end have YASM
     fi # end !WINNT_x86_MSVC
 
     if test -n "$VPX_X86_ASM"; then
       AC_DEFINE(VPX_X86_ASM)
     else
@@ -8705,17 +8711,16 @@ AC_SUBST(JAVA_INCLUDE_PATH)
 AC_SUBST(JAVA)
 AC_SUBST(JAVAC)
 AC_SUBST(JAR)
 
 AC_SUBST(MOZ_PROFILELOCKING)
 
 AC_SUBST(HAVE_XIE)
 AC_SUBST(MOZ_XIE_LIBS)
-AC_SUBST(MOZ_ENABLE_POSTSCRIPT)
 
 AC_SUBST(BUILD_STATIC_LIBS)
 AC_SUBST(MOZ_ENABLE_LIBXUL)
 AC_SUBST(ENABLE_TESTS)
 AC_SUBST(IBMBIDI)
 AC_SUBST(MOZ_UNIVERSALCHARDET)
 AC_SUBST(ACCESSIBILITY)
 AC_SUBST(MOZ_VIEW_SOURCE)
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -58,16 +58,17 @@
 #include "nsIObserver.h"
 #include "nsGkAtoms.h"
 #include "nsAutoPtr.h"
 #include "nsPIDOMWindow.h"
 #ifdef MOZ_SMIL
 #include "nsSMILAnimationController.h"
 #endif // MOZ_SMIL
 #include "nsIScriptGlobalObject.h"
+#include "nsIDocumentEncoder.h"
 
 class nsIContent;
 class nsPresContext;
 class nsIPresShell;
 class nsIDocShell;
 class nsStyleSet;
 class nsIStyleSheet;
 class nsIStyleRule;
@@ -110,19 +111,20 @@ class Loader;
 } // namespace css
 
 namespace dom {
 class Link;
 class Element;
 } // namespace dom
 } // namespace mozilla
 
+
 #define NS_IDOCUMENT_IID      \
-{ 0x3ee6a14b, 0x83b5, 0x4629, \
-  { 0x96, 0x9b, 0xe9, 0x84, 0x7c, 0x57, 0x24, 0x3c } }
+{ 0x1d8bd3d4, 0x6f6d, 0x49fe, \
+  { 0xaf, 0xda, 0xc9, 0x4a, 0xef, 0x8f, 0xcf, 0x1f } }
 
 // 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              (1 << 0)
@@ -432,17 +434,17 @@ public:
    * presshell if the presshell should observe document mutations.
    */
   virtual nsresult CreateShell(nsPresContext* aContext,
                                nsIViewManager* aViewManager,
                                nsStyleSet* aStyleSet,
                                nsIPresShell** aInstancePtrResult) = 0;
   void DeleteShell() { mPresShell = nsnull; }
 
-  nsIPresShell* GetPrimaryShell() const
+  nsIPresShell* GetShell() const
   {
     return mShellIsHidden ? nsnull : mPresShell;
   }
 
   void SetShellHidden(PRBool aHide) { mShellIsHidden = aHide; }
   PRBool ShellIsHidden() const { return mShellIsHidden; }
 
   /**
@@ -1108,16 +1110,26 @@ public:
   virtual already_AddRefed<nsIParser> GetFragmentParser() {
     return nsnull;
   }
 
   virtual void SetFragmentParser(nsIParser* aParser) {
     // Do nothing.
   }
 
+  already_AddRefed<nsIDocumentEncoder> GetCachedEncoder()
+  {
+    return mCachedEncoder.forget();
+  }
+
+  void SetCachedEncoder(nsIDocumentEncoder* aEncoder)
+  {
+    mCachedEncoder = aEncoder;
+  }
+
   // In case of failure, the document really can't initialize the frame loader.
   virtual nsresult InitializeFrameLoader(nsFrameLoader* aLoader) = 0;
   // In case of failure, the caller must handle the error, for example by
   // finalizing frame loader asynchronously.
   virtual nsresult FinalizeFrameLoader(nsFrameLoader* aLoader) = 0;
   // Removes the frame loader of aShell from the initialization list.
   virtual void TryCancelFrameLoaderInitialization(nsIDocShell* aShell) = 0;
   //  Returns true if the frame loader of aShell is in the finalization list.
@@ -1144,17 +1156,17 @@ public:
   }
   
   /**
    * Set the display document for this document.  aDisplayDocument must not be
    * null.
    */
   void SetDisplayDocument(nsIDocument* aDisplayDocument)
   {
-    NS_PRECONDITION(!GetPrimaryShell() &&
+    NS_PRECONDITION(!GetShell() &&
                     !nsCOMPtr<nsISupports>(GetContainer()) &&
                     !GetWindow() &&
                     !GetScriptGlobalObject(),
                     "Shouldn't set mDisplayDocument on documents that already "
                     "have a presentation or a docshell or a window");
     NS_PRECONDITION(aDisplayDocument != this, "Should be different document");
     NS_PRECONDITION(!aDisplayDocument->GetDisplayDocument(),
                     "Display documents should not nest");
@@ -1415,16 +1427,27 @@ protected:
   virtual void MutationEventDispatched(nsINode* aTarget) = 0;
   friend class mozAutoSubtreeModified;
 
   virtual Element* GetNameSpaceElement()
   {
     return GetRootElement();
   }
 
+  void SetContentTypeInternal(const nsACString& aType)
+  {
+    mCachedEncoder = nsnull;
+    mContentType = aType;
+  }
+
+  nsCString GetContentTypeInternal() const
+  {
+    return mContentType;
+  }
+
   nsCOMPtr<nsIURI> mDocumentURI;
   nsCOMPtr<nsIURI> mDocumentBaseURI;
 
   nsWeakPtr mDocumentLoadGroup;
 
   nsWeakPtr mDocumentContainer;
 
   nsCString mCharacterSet;
@@ -1523,17 +1546,19 @@ protected:
   // document.
   nsCOMPtr<nsIDocument> mOriginalDocument;
 
   // The bidi options for this document.  What this bitfield means is
   // defined in nsBidiUtils.h
   PRUint32 mBidiOptions;
 
   nsCString mContentLanguage;
+private:
   nsCString mContentType;
+protected:
 
   // The document's security info
   nsCOMPtr<nsISupports> mSecurityInfo;
 
   // if this document is part of a multipart document,
   // the ID can be used to distinguish it from the other parts.
   PRUint32 mPartID;
   
@@ -1553,16 +1578,18 @@ protected:
 
   PRUint32 mEventsSuppressed;
 
   nsString mPendingStateObject;
 
   // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
   // updated on every set of mSecriptGlobalObject.
   nsPIDOMWindow *mWindow;
+
+  nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsIDocument, NS_IDOCUMENT_IID)
 
 /**
  * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
  * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
  * object is deleted.
--- a/content/base/public/nsIDocumentEncoder.idl
+++ b/content/base/public/nsIDocumentEncoder.idl
@@ -39,16 +39,23 @@
 #include "nsISupports.idl"
 
 interface nsIDOMDocument;
 interface nsIDOMRange;
 interface nsISelection;
 interface nsIDOMNode;
 interface nsIOutputStream;
 
+%{ C++
+class nsINode;
+class nsIDocument;
+%}
+[ptr] native nsINodePtr(nsINode);
+[ptr] native nsIDocumentPtr(nsIDocument);
+
 [scriptable, uuid(c0da5b87-0ba7-4d7c-8cb3-fcb02af4253d)]
 interface nsIDocumentEncoderNodeFixup : nsISupports
 {
   /**
    * Create a fixed up version of a node. This method is called before
    * each node in a document is about to be persisted. The implementor
    * may return a new node with fixed up attributes or null. If null is
    * returned the node should be used as-is.
@@ -56,17 +63,17 @@ interface nsIDocumentEncoderNodeFixup : 
    * @param [OUT] aSerializeCloneKids True if the document encoder should
    * apply recursive serialization to the children of the fixed up node
    * instead of the children of the original node.
    * @return The resulting fixed up node.
    */
   nsIDOMNode fixupNode(in nsIDOMNode aNode, out boolean aSerializeCloneKids);
 };
 
-[scriptable, uuid(794a81f6-bde6-4f76-9f5e-0ea0911a2d9f)]
+[scriptable, uuid(7222bdf1-c2b9-41f1-a40a-a3d65283a95b)]
 interface nsIDocumentEncoder : nsISupports
 {
   // Output methods flag bits. There are a frightening number of these,
   // because everyone wants something a little bit different
    
 
   /** 
    * Output only the selection (as opposed to the whole document).
@@ -233,16 +240,19 @@ interface nsIDocumentEncoder : nsISuppor
    * Initialize with a pointer to the document and the mime type.
    * @param aDocument Document to encode.
    * @param aMimeType MimeType to use. May also be set by SetMimeType.
    * @param aFlags Flags to use while encoding. May also be set by SetFlags.
    */
   void init(in nsIDOMDocument aDocument,
             in AString aMimeType,
             in unsigned long aFlags);
+  [noscript] void nativeInit(in nsIDocumentPtr aDocument,
+                             in AString aMimeType,
+                             in unsigned long aFlags);
 
   /**
    *  If the selection is set to a non-null value, then the
    *  selection is used for encoding, otherwise the entire
    *  document is encoded.
    * @param aSelection The selection to encode.
    */
   void setSelection(in nsISelection aSelection);
@@ -265,16 +275,17 @@ interface nsIDocumentEncoder : nsISuppor
 
   /**
    *  If the container is set to a non-null value, then its
    *  child nodes are used for encoding, otherwise the entire
    *  document or range or selection or node is encoded.
    *  @param aContainer The node which child nodes will be encoded.
    */
   void setContainerNode(in nsIDOMNode aContainer);
+  [noscript] void setNativeContainerNode(in nsINodePtr aContainer);
 
   /**
    *  Documents typically have an intrinsic character set,
    *  but if no intrinsic value is found, the platform character set
    *  is used. This function overrides both the intrinisc and platform
    *  charset.
    *  @param aCharset Overrides the both the intrinsic or platform
    *  character set when encoding the document.
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -528,17 +528,17 @@ nsContentSink::ProcessHeaderData(nsIAtom
   else if (aHeader == nsGkAtoms::link) {
     rv = ProcessLinkHeader(aContent, aValue);
   }
   else if (aHeader == nsGkAtoms::msthemecompatible) {
     // Disable theming for the presshell if the value is no.
     // XXXbz don't we want to support this as an HTTP header too?
     nsAutoString value(aValue);
     if (value.LowerCaseEqualsLiteral("no")) {
-      nsIPresShell* shell = mDocument->GetPrimaryShell();
+      nsIPresShell* shell = mDocument->GetShell();
       if (shell) {
         shell->DisableThemeSupport();
       }
     }
   }
   // Don't report "refresh" headers back to necko, since our document handles
   // them
   else if (aHeader != nsGkAtoms::refresh && mParser) {
@@ -1262,17 +1262,17 @@ nsContentSink::StartLayout(PRBool aIgnor
   // sure to flush tags instead of just calling UpdateChildCounts() after we
   // loop over the shells.
   FlushTags();
 
   mLayoutStarted = PR_TRUE;
   mLastNotificationTime = PR_Now();
 
   mDocument->SetMayStartLayout(PR_TRUE);
-  nsCOMPtr<nsIPresShell> shell = mDocument->GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> shell = mDocument->GetShell();
   // Make sure we don't call InitialReflow() for a shell that has
   // already called it. This can happen when the layout frame for
   // an iframe is constructed *between* the Embed() call for the
   // docshell in the iframe, and the content sink's call to OpenBody().
   // (Bug 153815)
   if (shell && !shell->DidInitialReflow()) {
     nsRect r = shell->GetPresContext()->GetVisibleArea();
     nsCOMPtr<nsIPresShell> shellGrip = shell;
@@ -1458,17 +1458,17 @@ nsContentSink::WillResumeImpl()
 nsresult
 nsContentSink::DidProcessATokenImpl()
 {
   if (!mCanInterruptParser || !mParser || !mParser->CanInterrupt()) {
     return NS_OK;
   }
 
   // Get the current user event time
-  nsIPresShell *shell = mDocument->GetPrimaryShell();
+  nsIPresShell *shell = mDocument->GetShell();
   if (!shell) {
     // If there's no pres shell in the document, return early since
     // we're not laying anything out here.
     return NS_OK;
   }
 
   // Increase before comparing to gEventProbeRate
   ++mDeflectedCount;
@@ -1626,17 +1626,17 @@ nsContentSink::IsScriptExecutingImpl()
 
 nsresult
 nsContentSink::WillParseImpl(void)
 {
   if (!mCanInterruptParser) {
     return NS_OK;
   }
 
-  nsIPresShell *shell = mDocument->GetPrimaryShell();
+  nsIPresShell *shell = mDocument->GetShell();
   if (!shell) {
     return NS_OK;
   }
 
   PRUint32 currentTime = PR_IntervalToMicroseconds(PR_IntervalNow());
 
   if (sEnablePerfMode == 0) {
     nsIViewManager* vm = shell->GetViewManager();
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -469,16 +469,17 @@ nsContentUtils::InitializeEventTable() {
 
   static const EventNameMapping eventArray[] = {
     { nsGkAtoms::onmousedown,                   NS_MOUSE_BUTTON_DOWN, EventNameType_All, NS_MOUSE_EVENT },
     { nsGkAtoms::onmouseup,                     NS_MOUSE_BUTTON_UP, EventNameType_All, NS_MOUSE_EVENT },
     { nsGkAtoms::onclick,                       NS_MOUSE_CLICK, EventNameType_All, NS_MOUSE_EVENT },
     { nsGkAtoms::ondblclick,                    NS_MOUSE_DOUBLECLICK, EventNameType_HTMLXUL, NS_MOUSE_EVENT },
     { nsGkAtoms::onmouseover,                   NS_MOUSE_ENTER_SYNTH, EventNameType_All, NS_MOUSE_EVENT },
     { nsGkAtoms::onmouseout,                    NS_MOUSE_EXIT_SYNTH, EventNameType_All, NS_MOUSE_EVENT },
+    { nsGkAtoms::onMozMouseHittest,             NS_MOUSE_MOZHITTEST, EventNameType_None, NS_MOUSE_EVENT },
     { nsGkAtoms::onmousemove,                   NS_MOUSE_MOVE, EventNameType_All, NS_MOUSE_EVENT },
     { nsGkAtoms::oncontextmenu,                 NS_CONTEXTMENU, EventNameType_HTMLXUL, NS_MOUSE_EVENT },
 
     { nsGkAtoms::onkeydown,                     NS_KEY_DOWN, EventNameType_HTMLXUL, NS_KEY_EVENT },
     { nsGkAtoms::onkeyup,                       NS_KEY_UP, EventNameType_HTMLXUL, NS_KEY_EVENT },
     { nsGkAtoms::onkeypress,                    NS_KEY_PRESS, EventNameType_HTMLXUL, NS_KEY_EVENT },
                                                 
     { nsGkAtoms::onfocus,                       NS_FOCUS_CONTENT, EventNameType_HTMLXUL, NS_FOCUS_EVENT },
@@ -490,16 +491,17 @@ nsContentUtils::InitializeEventTable() {
     { nsGkAtoms::onreset,                       NS_FORM_RESET, EventNameType_HTMLXUL, NS_EVENT },
     { nsGkAtoms::onchange,                      NS_FORM_CHANGE, EventNameType_HTMLXUL, NS_EVENT },
     { nsGkAtoms::onselect,                      NS_FORM_SELECTED, EventNameType_HTMLXUL, NS_EVENT },
     { nsGkAtoms::onload,                        NS_LOAD, EventNameType_All, NS_EVENT },
     { nsGkAtoms::onpopstate,                    NS_POPSTATE, EventNameType_HTMLXUL, NS_EVENT_NULL },
     { nsGkAtoms::onunload,                      NS_PAGE_UNLOAD,
                                                 (EventNameType_HTMLXUL | EventNameType_SVGSVG), NS_EVENT },
     { nsGkAtoms::onhashchange,                  NS_HASHCHANGE, EventNameType_HTMLXUL, NS_EVENT },
+    { nsGkAtoms::onreadystatechange,            NS_READYSTATECHANGE, EventNameType_HTMLXUL },
     { nsGkAtoms::onbeforeunload,                NS_BEFORE_PAGE_UNLOAD, EventNameType_HTMLXUL, NS_EVENT },
     { nsGkAtoms::onabort,                       NS_IMAGE_ABORT,
                                                 (EventNameType_HTMLXUL | EventNameType_SVGSVG), NS_EVENT },
     { nsGkAtoms::onerror,                       NS_LOAD_ERROR,
                                                 (EventNameType_HTMLXUL | EventNameType_SVGSVG), NS_EVENT },
 
     { nsGkAtoms::onDOMAttrModified,             NS_MUTATION_ATTRMODIFIED, EventNameType_HTMLXUL, NS_MUTATION_EVENT },
     { nsGkAtoms::onDOMCharacterDataModified,    NS_MUTATION_CHARACTERDATAMODIFIED, EventNameType_HTMLXUL, NS_MUTATION_EVENT },
@@ -2295,17 +2297,17 @@ nsContentUtils::SplitExpatName(const PRU
 }
 
 // static
 nsPresContext*
 nsContentUtils::GetContextForContent(nsIContent* aContent)
 {
   nsIDocument* doc = aContent->GetCurrentDoc();
   if (doc) {
-    nsIPresShell *presShell = doc->GetPrimaryShell();
+    nsIPresShell *presShell = doc->GetShell();
     if (presShell) {
       return presShell->GetPresContext();
     }
   }
   return nsnull;
 }
 
 // static
@@ -6111,17 +6113,17 @@ already_AddRefed<mozilla::layers::LayerM
 nsContentUtils::LayerManagerForDocument(nsIDocument *aDoc)
 {
   nsIDocument* doc = aDoc;
   nsIDocument* displayDoc = doc->GetDisplayDocument();
   if (displayDoc) {
     doc = displayDoc;
   }
 
-  nsIPresShell* shell = doc->GetPrimaryShell();
+  nsIPresShell* shell = doc->GetShell();
   nsCOMPtr<nsISupports> container = doc->GetContainer();
   nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem = do_QueryInterface(container);
   while (!shell && docShellTreeItem) {
     // We may be in a display:none subdocument, or we may not have a presshell
     // created yet.
     // Walk the docshell tree to find the nearest container that has a presshell,
     // and find the root widget from that.
     nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(docShellTreeItem);
--- a/content/base/src/nsCopySupport.cpp
+++ b/content/base/src/nsCopySupport.cpp
@@ -593,17 +593,17 @@ static nsresult AppendDOMNode(nsITransfe
   return AppendString(aTransferable, context, kHTMLContext);
 }
 
 nsIContent*
 nsCopySupport::GetSelectionForCopy(nsIDocument* aDocument, nsISelection** aSelection)
 {
   *aSelection = nsnull;
 
-  nsIPresShell* presShell = aDocument->GetPrimaryShell();
+  nsIPresShell* presShell = aDocument->GetShell();
   if (!presShell)
     return nsnull;
 
   // check if the focused node in the window has a selection
   nsCOMPtr<nsPIDOMWindow> focusedWindow;
   nsIContent* content =
     nsFocusManager::GetFocusedDescendant(aDocument->GetWindow(), PR_FALSE,
                                          getter_AddRefs(focusedWindow));
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -65,16 +65,17 @@
 #include "nsIBaseWindow.h"
 #include "nsCSSLoader.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIScriptRuntime.h"
 #include "nsCOMArray.h"
 
 #include "nsGUIEvent.h"
+#include "nsPLDOMEvent.h"
 
 #include "nsIDOMStyleSheet.h"
 #include "nsDOMAttribute.h"
 #include "nsIDOMDOMStringList.h"
 #include "nsIDOMDOMImplementation.h"
 #include "nsIDOMDocumentView.h"
 #include "nsIDOMAbstractView.h"
 #include "nsIDOMDocumentXBL.h"
@@ -1389,17 +1390,17 @@ nsDOMImplementation::Init(nsIURI* aDocum
 // ==================================================================
 
   // NOTE! nsDocument::operator new() zeroes out all members, so don't
   // bother initializing members to 0.
 
 nsDocument::nsDocument(const char* aContentType)
   : nsIDocument()
 {
-  mContentType = aContentType;
+  SetContentTypeInternal(nsDependentCString(aContentType));
   
 #ifdef PR_LOGGING
   if (!gDocumentLeakPRLog)
     gDocumentLeakPRLog = PR_NewLogModule("DocumentLeak");
 
   if (gDocumentLeakPRLog)
     PR_LOG(gDocumentLeakPRLog, PR_LOG_DEBUG,
            ("DOCUMENT %p created", this));
@@ -1684,16 +1685,17 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mStyleAttrStyleSheet, nsIStyleSheet)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mScriptEventManager)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mXPathEvaluatorTearoff)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLayoutHistoryState)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnloadBlocker)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFirstBaseNodeWithHref)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDOMImplementation)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOriginalDocument)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCachedEncoder)
 
   // Traverse all our nsCOMArrays.
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mStyleSheets)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mCatalogSheets)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mPreloadingImages)
 
 #ifdef MOZ_SMIL
   // Traverse animation components
@@ -1727,16 +1729,17 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(ns
   }
   tmp->mFirstChild = nsnull;
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCachedRootElement)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDisplayDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mFirstBaseNodeWithHref)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDOMImplementation)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOriginalDocument)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCachedEncoder)
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK_USERDATA
 
   tmp->mParentDocument = nsnull;
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mPreloadingImages)
 
   // nsDocument has a pretty complex destructor, so we're going to
@@ -1943,17 +1946,17 @@ nsDocument::ResetToURI(nsIURI *aURI, nsI
 
     // XXXbz what does "just fine" mean exactly?  And given that there
     // is no nsDocShell::SetDocument, what is this talking about?
   }
 
   mLastModified.Truncate();
   // XXXbz I guess we're assuming that the caller will either pass in
   // a channel with a useful type or call SetContentType?
-  mContentType.Truncate();
+  SetContentTypeInternal(EmptyCString());
   mContentLanguage.Truncate();
   mBaseTarget.Truncate();
   mReferrer.Truncate();
 
   mXMLDeclarationBits = 0;
 
   // Now get our new principal
   if (aPrincipal) {
@@ -1994,17 +1997,17 @@ nsDocument::ResetStylesheetsToURI(nsIURI
   }
 
   indx = mCatalogSheets.Count();
   while (--indx >= 0) {
     nsIStyleSheet* sheet = mCatalogSheets[indx];
     sheet->SetOwningDocument(nsnull);
 
     if (sheet->IsApplicable()) {
-      nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+      nsCOMPtr<nsIPresShell> shell = GetShell();
       if (shell) {
         shell->StyleSet()->RemoveStyleSheet(nsStyleSet::eAgentSheet, sheet);
       }
     }
 
     // XXX Tell observers?
   }
 
@@ -2015,33 +2018,33 @@ nsDocument::ResetStylesheetsToURI(nsIURI
   // now, but it could in the future -- in which case not releasing them
   // is probably the right thing to do.
 
   // Now reset our inline style and attribute sheets.
   nsresult rv = NS_OK;
   nsStyleSet::sheetType attrSheetType = GetAttrSheetType();
   if (mAttrStyleSheet) {
     // Remove this sheet from all style sets
-    nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+    nsCOMPtr<nsIPresShell> shell = GetShell();
     if (shell) {
       shell->StyleSet()->RemoveStyleSheet(attrSheetType, mAttrStyleSheet);
     }
     mAttrStyleSheet->Reset(aURI);
   } else {
     rv = NS_NewHTMLStyleSheet(getter_AddRefs(mAttrStyleSheet), aURI, this);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Don't use AddStyleSheet, since it'll put the sheet into style
   // sets in the document level, which is not desirable here.
   mAttrStyleSheet->SetOwningDocument(this);
   
   if (mStyleAttrStyleSheet) {
     // Remove this sheet from all style sets
-    nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+    nsCOMPtr<nsIPresShell> shell = GetShell();
     if (shell) {
       shell->StyleSet()->
         RemoveStyleSheet(nsStyleSet::eStyleAttrSheet, mStyleAttrStyleSheet);
     }
     mStyleAttrStyleSheet->Reset(aURI);
   } else {
     mStyleAttrStyleSheet = new nsHTMLCSSStyleSheet();
     NS_ENSURE_TRUE(mStyleAttrStyleSheet, NS_ERROR_OUT_OF_MEMORY);
@@ -2049,17 +2052,17 @@ nsDocument::ResetStylesheetsToURI(nsIURI
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // The loop over style sets below will handle putting this sheet
   // into style sets as needed.
   mStyleAttrStyleSheet->SetOwningDocument(this);
 
   // Now set up our style sets
-  nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     FillStyleSet(shell->StyleSet());
   }
 
   return rv;
 }
 
 nsStyleSet::sheetType
@@ -2151,17 +2154,17 @@ nsDocument::StartDocumentLoad(const char
   nsCAutoString contentType;
   if (NS_SUCCEEDED(aChannel->GetContentType(contentType))) {
     // XXX this is only necessary for viewsource:
     nsACString::const_iterator start, end, semicolon;
     contentType.BeginReading(start);
     contentType.EndReading(end);
     semicolon = start;
     FindCharInReadable(';', semicolon, end);
-    mContentType = Substring(start, semicolon);
+    SetContentTypeInternal(Substring(start, semicolon));
   }
 
   RetrieveRelevantHeaders(aChannel);
 
   mChannel = aChannel;
   
   nsresult rv = InitCSP();
   NS_ENSURE_SUCCESS(rv, rv);
@@ -2432,29 +2435,29 @@ nsDocument::SetApplicationCache(nsIAppli
   mApplicationCache = aApplicationCache;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocument::GetContentType(nsAString& aContentType)
 {
-  CopyUTF8toUTF16(mContentType, aContentType);
+  CopyUTF8toUTF16(GetContentTypeInternal(), aContentType);
 
   return NS_OK;
 }
 
 void
 nsDocument::SetContentType(const nsAString& aContentType)
 {
-  NS_ASSERTION(mContentType.IsEmpty() ||
-               mContentType.Equals(NS_ConvertUTF16toUTF8(aContentType)),
+  NS_ASSERTION(GetContentTypeInternal().IsEmpty() ||
+               GetContentTypeInternal().Equals(NS_ConvertUTF16toUTF8(aContentType)),
                "Do you really want to change the content-type?");
 
-  CopyUTF16toUTF8(aContentType, mContentType);
+  SetContentTypeInternal(NS_ConvertUTF16toUTF8(aContentType));
 }
 
 /* Return true if the document is in the focused top-level window, and is an
  * ancestor of the focused DOMWindow. */
 NS_IMETHODIMP
 nsDocument::HasFocus(PRBool* aResult)
 {
   *aResult = PR_FALSE;
@@ -2565,17 +2568,17 @@ nsDocument::ElementFromPointHelper(float
   nscoord y = nsPresContext::CSSPixelsToAppUnits(aY);
   nsPoint pt(x, y);
 
   // Make sure the layout information we get is up-to-date, and
   // ensure we get a root frame (for everything but XUL)
   if (aFlushLayout)
     FlushPendingNotifications(Flush_Layout);
 
-  nsIPresShell *ps = GetPrimaryShell();
+  nsIPresShell *ps = GetShell();
   NS_ENSURE_STATE(ps);
   nsIFrame *rootFrame = ps->GetRootFrame();
 
   // XUL docs, unlike HTML, have no frame tree until everything's done loading
   if (!rootFrame)
     return NS_OK; // return null to premature XUL callers as a reminder to wait
 
   nsIFrame *ptFrame = nsLayoutUtils::GetFrameForPoint(rootFrame, pt, PR_TRUE,
@@ -2635,17 +2638,17 @@ nsDocument::NodesFromRectHelper(float aX
   nsRect rect(x, y, w, h);
 
   // Make sure the layout information we get is up-to-date, and
   // ensure we get a root frame (for everything but XUL)
   if (aFlushLayout) {
     FlushPendingNotifications(Flush_Layout);
   }
 
-  nsIPresShell *ps = GetPrimaryShell();
+  nsIPresShell *ps = GetShell();
   NS_ENSURE_STATE(ps);
   nsIFrame *rootFrame = ps->GetRootFrame();
 
   // XUL docs, unlike HTML, have no frame tree until everything's done loading
   if (!rootFrame)
     return NS_OK; // return nothing to premature XUL callers as a reminder to wait
 
   nsTArray<nsIFrame*> outFrames;
@@ -3236,17 +3239,17 @@ PRInt32
 nsDocument::GetIndexOfStyleSheet(nsIStyleSheet* aSheet) const
 {
   return mStyleSheets.IndexOf(aSheet);
 }
 
 void
 nsDocument::AddStyleSheetToStyleSets(nsIStyleSheet* aSheet)
 {
-  nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     shell->StyleSet()->AddDocStyleSheet(aSheet, this);
   }
 }
 
 void
 nsDocument::AddStyleSheet(nsIStyleSheet* aSheet)
 {
@@ -3259,17 +3262,17 @@ nsDocument::AddStyleSheet(nsIStyleSheet*
   }
 
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetAdded, (this, aSheet, PR_TRUE));
 }
 
 void
 nsDocument::RemoveStyleSheetFromStyleSets(nsIStyleSheet* aSheet)
 {
-  nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     shell->StyleSet()->RemoveStyleSheet(nsStyleSet::eDocSheet, aSheet);
   }
 }
 
 void
 nsDocument::RemoveStyleSheet(nsIStyleSheet* aSheet)
 {
@@ -3387,17 +3390,17 @@ nsDocument::GetCatalogStyleSheetAt(PRInt
 void
 nsDocument::AddCatalogStyleSheet(nsIStyleSheet* aSheet)
 {
   mCatalogSheets.AppendObject(aSheet);
   aSheet->SetOwningDocument(this);
 
   if (aSheet->IsApplicable()) {
     // This is like |AddStyleSheetToStyleSets|, but for an agent sheet.
-    nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+    nsCOMPtr<nsIPresShell> shell = GetShell();
     if (shell) {
       shell->StyleSet()->AppendStyleSheet(nsStyleSet::eAgentSheet, aSheet);
     }
   }
                                                                                 
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetAdded, (this, aSheet, PR_FALSE));
 }
 
@@ -3856,17 +3859,17 @@ nsDocument::DispatchContentLoadedEvents(
         // target is not in the same document, so the event would never reach
         // the ancestor document if we used the normal event
         // dispatching code.
 
         nsEvent* innerEvent = privateEvent->GetInternalNSEvent();
         if (innerEvent) {
           nsEventStatus status = nsEventStatus_eIgnore;
 
-          nsIPresShell *shell = parent->GetPrimaryShell();
+          nsIPresShell *shell = parent->GetShell();
           if (shell) {
             nsRefPtr<nsPresContext> context = shell->GetPresContext();
 
             if (context) {
               nsEventDispatcher::Dispatch(parent, context, innerEvent, event,
                                           &status);
             }
           }
@@ -4944,17 +4947,17 @@ void
 nsDocument::DoNotifyPossibleTitleChange()
 {
   mPendingTitleChangeEvent.Forget();
   mHaveFiredTitleChange = PR_TRUE;
 
   nsAutoString title;
   GetTitle(title);
 
-  nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     nsCOMPtr<nsISupports> container = shell->GetPresContext()->GetContainer();
     if (container) {
       nsCOMPtr<nsIBaseWindow> docShellWin = do_QueryInterface(container);
       if (docShellWin) {
         docShellWin->SetTitle(PromiseFlatString(title).get());
       }
     }
@@ -5218,17 +5221,17 @@ nsDocument::GetAnimationController()
   // for data documents.
   if (!NS_SMILEnabled() || mLoadedAsData || mLoadedAsInteractiveData)
     return nsnull;
 
   mAnimationController = NS_NewSMILAnimationController(this);
   
   // If there's a presContext then check the animation mode and pause if
   // necessary.
-  nsIPresShell *shell = GetPrimaryShell();
+  nsIPresShell *shell = GetShell();
   if (mAnimationController && shell) {
     nsPresContext *context = shell->GetPresContext();
     if (context &&
         context->ImageAnimationMode() == imgIContainer::kDontAnimMode) {
       mAnimationController->Pause(nsSMILTimeContainer::PAUSE_USERPREF);
     }
   }
 
@@ -5275,17 +5278,17 @@ NS_IMETHODIMP
 nsDocument::SetDir(const nsAString& aDirection)
 {
   PRUint32 options = GetBidiOptions();
 
   for (const DirTable* elt = dirAttributes; elt->mName; elt++) {
     if (aDirection == NS_ConvertASCIItoUTF16(elt->mName)) {
       if (GET_BIDI_OPTION_DIRECTION(options) != elt->mValue) {
         SET_BIDI_OPTION_DIRECTION(options, elt->mValue);
-        nsIPresShell *shell = GetPrimaryShell();
+        nsIPresShell *shell = GetShell();
         if (shell) {
           nsPresContext *context = shell->GetPresContext();
           NS_ENSURE_TRUE(context, NS_ERROR_UNEXPECTED);
           context->SetBidi(options, PR_TRUE);
         } else {
           // No presentation; just set it on ourselves
           SetBidiOptions(options);
         }
@@ -5956,17 +5959,17 @@ nsDocument::RemoveEventListener(const ns
 {
   return RemoveGroupedEventListener(aType, aListener, aUseCapture, nsnull);
 }
 
 NS_IMETHODIMP
 nsDocument::DispatchEvent(nsIDOMEvent* aEvent, PRBool *_retval)
 {
   // Obtain a presentation context
-  nsIPresShell *shell = GetPrimaryShell();
+  nsIPresShell *shell = GetShell();
   nsRefPtr<nsPresContext> context;
   if (shell) {
      context = shell->GetPresContext();
   }
 
   nsEventStatus status = nsEventStatus_eIgnore;
   nsresult rv =
     nsEventDispatcher::DispatchDOMEvent(static_cast<nsINode*>(this),
@@ -6041,17 +6044,17 @@ nsDocument::AddEventListener(const nsASt
 NS_IMETHODIMP
 nsDocument::CreateEvent(const nsAString& aEventType, nsIDOMEvent** aReturn)
 {
   NS_ENSURE_ARG_POINTER(aReturn);
   *aReturn = nsnull;
 
   // Obtain a presentation shell
 
-  nsIPresShell *shell = GetPrimaryShell();
+  nsIPresShell *shell = GetShell();
 
   nsPresContext *presContext = nsnull;
 
   if (shell) {
     // Retrieve the context
     presContext = shell->GetPresContext();
   }
 
@@ -6111,17 +6114,17 @@ nsDocument::FlushPendingNotifications(mo
   // correct size to determine the correct style.
   if (mParentDocument && IsSafeToFlush()) {
     mozFlushType parentType = aType;
     if (aType >= Flush_Style)
       parentType = NS_MAX(Flush_Layout, aType);
     mParentDocument->FlushPendingNotifications(parentType);
   }
 
-  nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     shell->FlushPendingNotifications(aType);
   }
 }
 
 static PRBool
 Flush(nsIDocument* aDocument, void* aData)
 {
@@ -6541,17 +6544,17 @@ nsDocument::CreateElem(nsIAtom *aName, n
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
 
   return NS_NewElement(aResult, elementType, nodeInfo, PR_FALSE);
 }
 
 PRBool
 nsDocument::IsSafeToFlush() const
 {
-  nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> shell = GetShell();
   if (!shell)
     return PR_TRUE;
 
   return shell->IsSafeToFlush();
 }
 
 nsresult
 nsDocument::Sanitize()
@@ -7301,31 +7304,36 @@ nsDocument::CloneDocHelper(nsDocument* c
   // Misc state
 
   // State from nsIDocument
   clone->mCharacterSet = mCharacterSet;
   clone->mCharacterSetSource = mCharacterSetSource;
   clone->mCompatMode = mCompatMode;
   clone->mBidiOptions = mBidiOptions;
   clone->mContentLanguage = mContentLanguage;
-  clone->mContentType = mContentType;
+  clone->SetContentTypeInternal(GetContentTypeInternal());
   clone->mSecurityInfo = mSecurityInfo;
 
   // State from nsDocument
   clone->mIsRegularHTML = mIsRegularHTML;
   clone->mXMLDeclarationBits = mXMLDeclarationBits;
   clone->mBaseTarget = mBaseTarget;
   return NS_OK;
 }
 
 void
 nsDocument::SetReadyStateInternal(ReadyState rs)
 {
   mReadyState = rs;
-  // TODO fire "readystatechange"
+
+  nsRefPtr<nsPLDOMEvent> plevent =
+    new nsPLDOMEvent(this, NS_LITERAL_STRING("readystatechange"), PR_FALSE, PR_FALSE); 
+  if (plevent) {
+    plevent->RunDOMEventWhenSafe();
+  }
 }
 
 nsIDocument::ReadyState
 nsDocument::GetReadyStateEnum()
 {
   return mReadyState;
 }
 
@@ -7368,17 +7376,17 @@ FireOrClearDelayedEvents(nsTArray<nsCOMP
 {
   nsIFocusManager* fm = nsFocusManager::GetFocusManager();
   if (!fm)
     return;
 
   for (PRUint32 i = 0; i < aDocuments.Length(); ++i) {
     if (!aDocuments[i]->EventHandlingSuppressed()) {
       fm->FireDelayedEvents(aDocuments[i]);
-      nsCOMPtr<nsIPresShell> shell = aDocuments[i]->GetPrimaryShell();
+      nsCOMPtr<nsIPresShell> shell = aDocuments[i]->GetShell();
       if (shell) {
         shell->FireOrClearDelayedEvents(aFireEvents);
       }
     }
   }
 }
 
 void
@@ -7418,17 +7426,17 @@ nsDocument::GetDocumentState()
 {
   if (!(mGotDocumentState & NS_DOCUMENT_STATE_RTL_LOCALE)) {
     if (IsDocumentRightToLeft()) {
       mDocumentState |= NS_DOCUMENT_STATE_RTL_LOCALE;
     }
     mGotDocumentState |= NS_DOCUMENT_STATE_RTL_LOCALE;
   }
   if (!(mGotDocumentState & NS_DOCUMENT_STATE_WINDOW_INACTIVE)) {
-    nsIPresShell* shell = GetPrimaryShell();
+    nsIPresShell* shell = GetShell();
     if (shell && shell->GetPresContext() &&
         shell->GetPresContext()->IsTopLevelWindowInactive()) {
       mDocumentState |= NS_DOCUMENT_STATE_WINDOW_INACTIVE;
     }
     mGotDocumentState |= NS_DOCUMENT_STATE_WINDOW_INACTIVE;
   }
   return mDocumentState;
 }
@@ -7583,17 +7591,17 @@ nsDocument::ScrollToRef()
   unescapedRef.Assign(tmpstr);
   nsMemory::Free(tmpstr);
 
   nsresult rv = NS_ERROR_FAILURE;
   // We assume that the bytes are in UTF-8, as it says in the spec:
   // http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.1
   NS_ConvertUTF8toUTF16 ref(unescapedRef);
 
-  nsCOMPtr<nsIPresShell> shell = GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     // Check an empty string which might be caused by the UTF-8 conversion
     if (!ref.IsEmpty()) {
       // Note that GoToAnchor will handle flushing layout as needed.
       rv = shell->GoToAnchor(ref, mChangeScrollPosWhenScrollingToRef);
     } else {
       rv = NS_ERROR_FAILURE;
     }
--- a/content/base/src/nsDocumentEncoder.cpp
+++ b/content/base/src/nsDocumentEncoder.cpp
@@ -76,36 +76,37 @@
 #include "nsISelection.h"
 #include "nsISelectionPrivate.h"
 #include "nsITransferable.h" // for kUnicodeMime
 #include "nsContentUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsReadableUtils.h"
 #include "nsTArray.h"
 #include "nsIFrame.h"
+#include "nsStringBuffer.h"
 
 nsresult NS_NewDomSelection(nsISelection **aDomSelection);
 
 enum nsRangeIterationDirection {
   kDirectionOut = -1,
   kDirectionIn = 1
 };
 
 class nsDocumentEncoder : public nsIDocumentEncoder
 {
 public:
   nsDocumentEncoder();
   virtual ~nsDocumentEncoder();
 
-  NS_DECL_ISUPPORTS
-
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTION_CLASS(nsDocumentEncoder)
   NS_DECL_NSIDOCUMENTENCODER
 
 protected:
-  void Initialize();
+  void Initialize(PRBool aClearCachedSerializer = PR_TRUE);
   nsresult SerializeNodeStart(nsINode* aNode, PRInt32 aStartOffset,
                               PRInt32 aEndOffset, nsAString& aStr,
                               nsINode* aOriginalNode = nsnull);
   nsresult SerializeToStringRecursive(nsINode* aNode,
                                       nsAString& aStr,
                                       PRBool aDontSerializeRoot);
   nsresult SerializeNodeEnd(nsINode* aNode, nsAString& aStr);
   nsresult SerializeRangeToString(nsIRange *aRange,
@@ -170,61 +171,99 @@ protected:
   nsAutoTArray<nsINode*, 8>    mCommonAncestors;
   nsAutoTArray<nsIContent*, 8> mStartNodes;
   nsAutoTArray<PRInt32, 8>     mStartOffsets;
   nsAutoTArray<nsIContent*, 8> mEndNodes;
   nsAutoTArray<PRInt32, 8>     mEndOffsets;
   PRPackedBool      mHaltRangeHint;  
   PRPackedBool      mIsCopying;  // Set to PR_TRUE only while copying
   PRPackedBool      mNodeIsContainer;
+  nsStringBuffer*   mCachedBuffer;
 };
 
-NS_IMPL_ADDREF(nsDocumentEncoder)
-NS_IMPL_RELEASE(nsDocumentEncoder)
+NS_IMPL_CYCLE_COLLECTION_CLASS(nsDocumentEncoder)
 
-NS_INTERFACE_MAP_BEGIN(nsDocumentEncoder)
+NS_IMPL_CYCLE_COLLECTING_ADDREF(nsDocumentEncoder)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(nsDocumentEncoder)
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDocumentEncoder)
    NS_INTERFACE_MAP_ENTRY(nsIDocumentEncoder)
    NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
-nsDocumentEncoder::nsDocumentEncoder()
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDocumentEncoder)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDocument)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mSelection)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mRange)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mNode)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCommonParent)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsDocumentEncoder)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDocument)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mSelection)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mRange)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mNode)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCommonParent)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+nsDocumentEncoder::nsDocumentEncoder() : mCachedBuffer(nsnull)
 {
   Initialize();
   mMimeType.AssignLiteral("text/plain");
 
 }
 
-void nsDocumentEncoder::Initialize()
+void nsDocumentEncoder::Initialize(PRBool aClearCachedSerializer)
 {
   mFlags = 0;
   mWrapColumn = 72;
   mStartDepth = 0;
   mEndDepth = 0;
   mStartRootIndex = 0;
   mEndRootIndex = 0;
   mHaltRangeHint = PR_FALSE;
   mNodeIsContainer = PR_FALSE;
+  if (aClearCachedSerializer) {
+    mSerializer = nsnull;
+  }
 }
 
 nsDocumentEncoder::~nsDocumentEncoder()
 {
+  if (mCachedBuffer) {
+    mCachedBuffer->Release();
+  }
 }
 
 NS_IMETHODIMP
 nsDocumentEncoder::Init(nsIDOMDocument* aDocument,
                         const nsAString& aMimeType,
                         PRUint32 aFlags)
 {
   if (!aDocument)
     return NS_ERROR_INVALID_ARG;
 
-  Initialize();
+  nsCOMPtr<nsIDocument> doc = do_QueryInterface(aDocument);
+  NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);
+
+  return NativeInit(doc, aMimeType, aFlags);
+}
 
-  mDocument = do_QueryInterface(aDocument);
-  NS_ENSURE_TRUE(mDocument, NS_ERROR_FAILURE);
+NS_IMETHODIMP
+nsDocumentEncoder::NativeInit(nsIDocument* aDocument,
+                              const nsAString& aMimeType,
+                              PRUint32 aFlags)
+{
+  if (!aDocument)
+    return NS_ERROR_INVALID_ARG;
+
+  Initialize(!mMimeType.Equals(aMimeType));
+
+  mDocument = aDocument;
 
   mMimeType = aMimeType;
 
   mFlags = aFlags;
   mIsCopying = PR_FALSE;
 
   return NS_OK;
 }
@@ -262,16 +301,24 @@ NS_IMETHODIMP
 nsDocumentEncoder::SetContainerNode(nsIDOMNode *aContainer)
 {
   mNodeIsContainer = PR_TRUE;
   mNode = do_QueryInterface(aContainer);
   return NS_OK;
 }
 
 NS_IMETHODIMP
+nsDocumentEncoder::SetNativeContainerNode(nsINode* aContainer)
+{
+  mNodeIsContainer = PR_TRUE;
+  mNode = aContainer;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsDocumentEncoder::SetCharset(const nsACString& aCharset)
 {
   mCharset = aCharset;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocumentEncoder::GetMimeType(nsAString& aMimeType)
@@ -923,21 +970,36 @@ nsDocumentEncoder::SerializeRangeToStrin
 NS_IMETHODIMP
 nsDocumentEncoder::EncodeToString(nsAString& aOutputString)
 {
   if (!mDocument)
     return NS_ERROR_NOT_INITIALIZED;
 
   aOutputString.Truncate();
 
-  nsCAutoString progId(NS_CONTENTSERIALIZER_CONTRACTID_PREFIX);
-  AppendUTF16toUTF8(mMimeType, progId);
+  nsString output;
+  static const size_t bufferSize = 2048;
+  if (!mCachedBuffer) {
+    mCachedBuffer = nsStringBuffer::Alloc(bufferSize);
+  }
+  NS_ASSERTION(!mCachedBuffer->IsReadonly(),
+               "DocumentEncoder shouldn't keep reference to non-readonly buffer!");
+  static_cast<PRUnichar*>(mCachedBuffer->Data())[0] = PRUnichar(0);
+  mCachedBuffer->ToString(0, output, PR_TRUE);
+  // output owns the buffer now!
+  mCachedBuffer = nsnull;
+  
 
-  mSerializer = do_CreateInstance(progId.get());
-  NS_ENSURE_TRUE(mSerializer, NS_ERROR_NOT_IMPLEMENTED);
+  if (!mSerializer) {
+    nsCAutoString progId(NS_CONTENTSERIALIZER_CONTRACTID_PREFIX);
+    AppendUTF16toUTF8(mMimeType, progId);
+
+    mSerializer = do_CreateInstance(progId.get());
+    NS_ENSURE_TRUE(mSerializer, NS_ERROR_NOT_IMPLEMENTED);
+  }
 
   nsresult rv = NS_OK;
 
   nsCOMPtr<nsIAtom> charsetAtom;
   if (!mCharset.IsEmpty()) {
     if (!mCharsetConverterManager) {
       mCharsetConverterManager = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
       NS_ENSURE_SUCCESS(rv, rv);
@@ -961,57 +1023,69 @@ nsDocumentEncoder::EncodeToString(nsAStr
       // Bug 236546: newlines not added when copying table cells into clipboard
       // Each selected cell shows up as a range containing a row with a single cell
       // get the row, compare it to previous row and emit </tr><tr> as needed
       range->GetStartContainer(getter_AddRefs(node));
       NS_ENSURE_TRUE(node, NS_ERROR_FAILURE);
       if (node != prevNode) {
         if (prevNode) {
           nsCOMPtr<nsINode> p = do_QueryInterface(prevNode);
-          rv = SerializeNodeEnd(p, aOutputString);
+          rv = SerializeNodeEnd(p, output);
           NS_ENSURE_SUCCESS(rv, rv);
           prevNode = nsnull;
         }
         nsCOMPtr<nsIContent> content = do_QueryInterface(node);
         if (content && content->Tag() == nsGkAtoms::tr) {
           nsCOMPtr<nsINode> n = do_QueryInterface(node);
-          rv = SerializeNodeStart(n, 0, -1, aOutputString);
+          rv = SerializeNodeStart(n, 0, -1, output);
           NS_ENSURE_SUCCESS(rv, rv);
           prevNode = node;
         }
       }
 
       nsCOMPtr<nsIRange> r = do_QueryInterface(range);
-      rv = SerializeRangeToString(r, aOutputString);
+      rv = SerializeRangeToString(r, output);
       NS_ENSURE_SUCCESS(rv, rv);
     }
     if (prevNode) {
       nsCOMPtr<nsINode> p = do_QueryInterface(prevNode);
-      rv = SerializeNodeEnd(p, aOutputString);
+      rv = SerializeNodeEnd(p, output);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     mSelection = nsnull;
   } else if (mRange) {
-      rv = SerializeRangeToString(mRange, aOutputString);
+      rv = SerializeRangeToString(mRange, output);
 
       mRange = nsnull;
   } else if (mNode) {
-    rv = SerializeToStringRecursive(mNode, aOutputString, mNodeIsContainer);
+    rv = SerializeToStringRecursive(mNode, output, mNodeIsContainer);
     mNode = nsnull;
   } else {
-    rv = mSerializer->AppendDocumentStart(mDocument, aOutputString);
+    rv = mSerializer->AppendDocumentStart(mDocument, output);
 
     if (NS_SUCCEEDED(rv)) {
-      rv = SerializeToStringRecursive(mDocument, aOutputString, PR_FALSE);
+      rv = SerializeToStringRecursive(mDocument, output, PR_FALSE);
     }
   }
 
   NS_ENSURE_SUCCESS(rv, rv);
-  rv = mSerializer->Flush(aOutputString);
+  rv = mSerializer->Flush(output);
+ 
+  if (NS_SUCCEEDED(rv)) {
+    aOutputString.Append(output.get(), output.Length());
+  }
+  mCachedBuffer = nsStringBuffer::FromString(output);
+  // Try to cache the buffer.
+  if (mCachedBuffer && mCachedBuffer->StorageSize() == bufferSize &&
+      !mCachedBuffer->IsReadonly()) {
+    mCachedBuffer->AddRef();
+  } else {
+    mCachedBuffer = nsnull;
+  }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsDocumentEncoder::EncodeToStream(nsIOutputStream* aStream)
 {
   nsresult rv = NS_OK;
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -1007,18 +1007,18 @@ nsFrameLoader::SwapWithOtherLoader(nsFra
   if (!ourDoc || !otherDoc) {
     // Again, how odd, given that we had docshells
     return NS_ERROR_NOT_IMPLEMENTED;
   }
 
   NS_ASSERTION(ourDoc == ourParentDocument, "Unexpected parent document");
   NS_ASSERTION(otherDoc == otherParentDocument, "Unexpected parent document");
 
-  nsIPresShell* ourShell = ourDoc->GetPrimaryShell();
-  nsIPresShell* otherShell = otherDoc->GetPrimaryShell();
+  nsIPresShell* ourShell = ourDoc->GetShell();
+  nsIPresShell* otherShell = otherDoc->GetShell();
   if (!ourShell || !otherShell) {
     return NS_ERROR_NOT_IMPLEMENTED;
   }
 
   if (mInSwap || aOther->mInSwap) {
     return NS_ERROR_NOT_IMPLEMENTED;
   }
   mInSwap = aOther->mInSwap = PR_TRUE;
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -842,17 +842,17 @@ nsIContent::GetDesiredIMEState()
   // This is in another editable content, use the result of it.
   if (editableAncestor) {
     return editableAncestor->GetDesiredIMEState();
   }
   nsIDocument* doc = GetCurrentDoc();
   if (!doc) {
     return IME_STATUS_DISABLE;
   }
-  nsIPresShell* ps = doc->GetPrimaryShell();
+  nsIPresShell* ps = doc->GetShell();
   if (!ps) {
     return IME_STATUS_DISABLE;
   }
   nsPresContext* pc = ps->GetPresContext();
   if (!pc) {
     return IME_STATUS_DISABLE;
   }
   nsIEditor* editor = GetHTMLEditor(pc);
@@ -3296,17 +3296,17 @@ nsGenericElement::SetSMILOverrideStyleRu
   slots->mSMILOverrideStyleRule = aStyleRule;
 
   if (aNotify) {
     nsIDocument* doc = GetCurrentDoc();
     // Only need to request a restyle if we're in a document.  (We might not
     // be in a document, if we're clearing animation effects on a target node
     // that's been detached since the previous animation sample.)
     if (doc) {
-      nsCOMPtr<nsIPresShell> shell = doc->GetPrimaryShell();
+      nsCOMPtr<nsIPresShell> shell = doc->GetShell();
       if (shell) {
         shell->RestyleForAnimation(this);
       }
     }
   }
 
   return NS_OK;
 }
@@ -3616,17 +3616,17 @@ nsINode::doRemoveChildAt(PRUint32 aIndex
                          nsIContent* aKid, nsAttrAndChildArray& aChildArray,
                          PRBool aMutationEvent)
 {
   nsIDocument* doc = GetCurrentDoc();
 #ifdef ACCESSIBILITY
   // A11y needs to be notified of content removals first, so accessibility
   // events can be fired before any changes occur
   if (aNotify && doc) {
-    nsIPresShell *presShell = doc->GetPrimaryShell();
+    nsIPresShell *presShell = doc->GetShell();
     if (presShell && presShell->IsAccessibilityActive()) {
       nsCOMPtr<nsIAccessibilityService> accService = 
         do_GetService("@mozilla.org/accessibilityService;1");
       if (accService) {
         accService->InvalidateSubtreeFor(presShell, aKid,
                                          nsIAccessibilityService::NODE_REMOVE);
       }
     }
@@ -5373,17 +5373,17 @@ ParseSelectorList(nsINode* aNode,
       slot = &cur->mNext;
     }
   } while (*slot);
   *aSelectorList = selectorList;
 
   // It's not strictly necessary to have a prescontext here, but it's
   // a bit of an optimization for various stuff.
   *aPresContext = nsnull;
-  nsIPresShell* shell = doc->GetPrimaryShell();
+  nsIPresShell* shell = doc->GetShell();
   if (shell) {
     *aPresContext = shell->GetPresContext();
   }
 
   return NS_OK;
 }
 
 /*
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -658,32 +658,34 @@ GK_ATOM(onkeyup, "onkeyup")
 GK_ATOM(onLoad, "onLoad")
 GK_ATOM(onload, "onload")
 GK_ATOM(onpopstate, "onpopstate")
 GK_ATOM(only, "only")               // this one is not an event
 GK_ATOM(onmousedown, "onmousedown")
 GK_ATOM(onmousemove, "onmousemove")
 GK_ATOM(onmouseout, "onmouseout")
 GK_ATOM(onmouseover, "onmouseover")
+GK_ATOM(onMozMouseHittest, "onMozMouseHittest")
 GK_ATOM(onmouseup, "onmouseup")
 GK_ATOM(onMozAfterPaint, "onMozAfterPaint")
 GK_ATOM(onMozMousePixelScroll, "onMozMousePixelScroll")
 GK_ATOM(onMozScrolledAreaChanged, "onMozScrolledAreaChanged")
 GK_ATOM(ononline, "ononline")
 GK_ATOM(onoffline, "onoffline")
 GK_ATOM(onoverflow, "onoverflow")
 GK_ATOM(onoverflowchanged, "onoverflowchanged")
 GK_ATOM(onpagehide, "onpagehide")
 GK_ATOM(onpageshow, "onpageshow")
 GK_ATOM(onpaint, "onpaint")
 GK_ATOM(onpaste, "onpaste")
 GK_ATOM(onpopuphidden, "onpopuphidden")
 GK_ATOM(onpopuphiding, "onpopuphiding")
 GK_ATOM(onpopupshowing, "onpopupshowing")
 GK_ATOM(onpopupshown, "onpopupshown")
+GK_ATOM(onreadystatechange, "onreadystatechange")
 GK_ATOM(onRequest, "onRequest")
 GK_ATOM(onreset, "onreset")
 GK_ATOM(onresize, "onresize")
 GK_ATOM(onscroll, "onscroll")
 GK_ATOM(onselect, "onselect")
 GK_ATOM(onset, "onset")
 GK_ATOM(onsubmit, "onsubmit")
 GK_ATOM(ontext, "ontext")
--- a/content/base/src/nsImageLoadingContent.cpp
+++ b/content/base/src/nsImageLoadingContent.cpp
@@ -286,17 +286,17 @@ nsImageLoadingContent::OnStopDecode(imgI
   // by blocking onload until all in progress decodes get at least one frame
   // decoded. However, if all the data comes in while painting is suppressed
   // (ie, before the initial paint delay is finished), we fire onload without
   // doing a paint first. This means that decode-on-draw images don't start
   // decoding, so we can't wait for them to finish. See bug 512435.
 
   // We can only do this if we have a presshell
   nsIDocument* doc = GetOurDocument();
-  nsIPresShell* shell = doc ? doc->GetPrimaryShell() : nsnull;
+  nsIPresShell* shell = doc ? doc->GetShell() : nsnull;
   if (shell) {
 
     // We need to figure out whether to kick off decoding
     PRBool doRequestDecode = PR_FALSE;
 
     // If we haven't got the initial reflow yet, IsPaintingSuppressed actually
     // returns false
     if (!shell->DidInitialReflow())
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -871,17 +871,17 @@ nsObjectLoadingContent::EnsureInstantiat
 
     nsIDocument* doc = thisContent->GetCurrentDoc();
     if (!doc) {
       // Nothing we can do while plugin loading is done in layout...
       mInstantiating = PR_FALSE;
       return NS_OK;
     }
 
-    nsCOMPtr<nsIPresShell> shell = doc->GetPrimaryShell();
+    nsCOMPtr<nsIPresShell> shell = doc->GetShell();
     if (shell) {
       shell->RecreateFramesFor(thisContent);
     }
 
     mInstantiating = PR_FALSE;
 
     frame = GetExistingFrame(eFlushContent);
     if (!frame) {
@@ -1651,17 +1651,17 @@ nsObjectLoadingContent::NotifyStateChang
     if (aSync) {
       // Make sure that frames are actually constructed, and do it after
       // EndUpdate was called.
       doc->FlushPendingNotifications(Flush_Frames);
     }
   } else if (aOldType != mType) {
     // If our state changed, then we already recreated frames
     // Otherwise, need to do that here
-    nsCOMPtr<nsIPresShell> shell = doc->GetPrimaryShell();
+    nsCOMPtr<nsIPresShell> shell = doc->GetShell();
     if (shell) {
       shell->RecreateFramesFor(thisContent);
     }
   }
 }
 
 /* static */ void
 nsObjectLoadingContent::FirePluginError(nsIContent* thisContent,
--- a/content/base/src/nsWebSocket.cpp
+++ b/content/base/src/nsWebSocket.cpp
@@ -97,17 +97,17 @@ static nsIThread *gWebSocketThread = nsn
 // nsWebSocketEstablishedConnection
 ////////////////////////////////////////////////////////////////////////////////
 
 #define DEFAULT_BUFFER_SIZE 2048
 #define UTF_8_REPLACEMENT_CHAR    static_cast<PRUnichar>(0xFFFD)
 
 #define TIMEOUT_TRY_CONNECT_AGAIN         1000
 #define TIMEOUT_WAIT_FOR_SERVER_RESPONSE  20000
-#define TIMEOUT_WAIT_FOR_CLOSING          5000
+#define TIMEOUT_WAIT_FOR_CLOSING          20000
 
 #define ENSURE_TRUE_AND_FAIL_IF_FAILED(x, ret)                            \
   PR_BEGIN_MACRO                                                          \
     if (NS_UNLIKELY(!(x))) {                                              \
        NS_WARNING("ENSURE_TRUE_AND_FAIL_IF_FAILED(" #x ") failed");       \
        FailConnection();                                                  \
        return ret;                                                        \
     }                                                                     \
@@ -235,29 +235,43 @@ public:
   NS_IMETHOD SetProxyCredentials(const nsACString & aCredentials);
   NS_IMETHOD SetWWWCredentials(const nsACString & aCredentials);
   NS_IMETHOD OnAuthAvailable();
   NS_IMETHOD OnAuthCancelled(PRBool userCancel);
 
   nsresult Init(nsWebSocket *aOwner);
   nsresult Disconnect();
 
-  // these are called always on the main thread (they dispatch themselves)
+  // These are called always on the main thread (they dispatch themselves).
+  // ATTENTION, this method when called can release both the WebSocket object
+  // (i.e. mOwner) and its connection (i.e. *this*) if there are no strong event
+  // listeners.
   DECL_RUNNABLE_ON_MAIN_THREAD_METHOD(Close)
   DECL_RUNNABLE_ON_MAIN_THREAD_METHOD(FailConnection)
 
   PRBool ClosedCleanly() { return mClosedCleanly; }
 
   nsresult PostMessage(const nsString& aMessage);
   PRUint32 GetOutgoingBufferedAmount() { return mOutgoingBufferedAmount; }
 
   // prevent more than one instance from connecting at a time per IP
   static nsTArray<nsRefPtr<nsWebSocketEstablishedConnection> >* sWSsConnecting;
 
 private:
+  enum WSFrameType {
+    eConnectFrame,
+    eUTF8MessageFrame,
+    eCloseFrame
+  };
+
+  struct nsWSFrame {
+    WSFrameType mType;
+    nsAutoPtr<nsCString> mData;
+  };
+
   // We can only establish one connection at a time per IP address.
   // TryConnect ensures this by checking sWSsConnecting.
   // If there is a IP address entry there it tries again after
   // TIMEOUT_TRY_CONNECT_AGAIN milliseconds.
   static void TryConnect(nsITimer *aTimer,
                          void     *aClosure);
 
   // We wait for the initial server response for
@@ -286,17 +300,18 @@ private:
   nsresult GenerateRequestKeys(nsCString& aKey1,
                                nsCString& aKey2,
                                nsCString& aKey3);
 
   PRBool UsingHttpProxy();
   nsresult Reset();
   void RemoveFromLoadGroup();
   nsresult ProcessHeaders();
-  nsresult PostData(nsCString *aBuffer, PRBool aIsMessage);
+  nsresult PostData(nsCString  *aBuffer,
+                    WSFrameType aWSFrameType);
   nsresult PrintErrorOnConsole(const char       *aBundleURI,
                                const PRUnichar  *aError,
                                const PRUnichar **aFormatStrings,
                                PRUint32          aFormatStringsLen);
   PRBool SentAlreadyTheCloseFrame()
   { return mPostedCloseFrame && mOutgoingMessages.GetSize() == 0; }
 
   // auth specific methods
@@ -319,17 +334,17 @@ private:
   // shared by both threads (the main and the socket ones)
   Mutex   mLockDisconnect;
   Mutex   mLockOutgoingMessages;
   Mutex   mLockReceivedMessages;
   nsCOMPtr<nsISocketTransport>    mSocketTransport;
   nsCOMPtr<nsIAsyncInputStream>   mSocketInput;
   nsCOMPtr<nsIAsyncOutputStream>  mSocketOutput;
   nsCOMPtr<nsIProxyInfo>          mProxyInfo;
-  nsDeque mOutgoingMessages; // has nsCString* which need to be sent
+  nsDeque mOutgoingMessages; // has nsWSFrame* which need to be sent
   PRUint32 mBytesAlreadySentOfFirstOutString;
   PRUint32 mOutgoingBufferedAmount; // not really necessary, but it is
                                     // here for fast access.
   nsDeque mReceivedMessages; // has nsCString* messages that need
                              // to be dispatched as message events
   nsCString mExpectedMD5Challenge;
   nsWebSocket* mOwner; // WEAK
 
@@ -647,41 +662,51 @@ nsWebSocketEstablishedConnection::nsWebS
   mStatus(CONN_NOT_CONNECTED)
 {
   NS_ASSERTION(NS_IsMainThread(), "Not running on main thread");
   nsLayoutStatics::AddRef();
 }
 
 nsWebSocketEstablishedConnection::~nsWebSocketEstablishedConnection()
 {
+  NS_ASSERTION(!mOwner, "Disconnect wasn't called!");
 }
 
 nsresult
 nsWebSocketEstablishedConnection::PostData(nsCString *aBuffer,
-                                           PRBool aIsMessage)
+                                           WSFrameType aWSFrameType)
 {
   NS_ASSERTION(NS_IsMainThread(), "Not running on main thread");
 
+  nsAutoPtr<nsCString> data(aBuffer);
+
   if (mStatus == CONN_CLOSED) {
     NS_ASSERTION(mOwner, "Posting data after disconnecting the websocket!");
     // the tcp connection has been closed, but the main thread hasn't received
     // the event for disconnecting the object yet.
     return NS_BASE_STREAM_CLOSED;
   }
 
   MutexAutoLock lockOut(mLockOutgoingMessages);
 
+  nsAutoPtr<nsWSFrame> frame(new nsWSFrame());
+  NS_ENSURE_TRUE(frame.get(), NS_ERROR_OUT_OF_MEMORY);
+  frame->mType = aWSFrameType;
+  frame->mData = data.forget();
+
   nsresult rv;
   PRInt32 sizeBefore = mOutgoingMessages.GetSize();
-  mOutgoingMessages.Push(aBuffer);
+  mOutgoingMessages.Push(frame.forget());
   NS_ENSURE_TRUE(mOutgoingMessages.GetSize() == sizeBefore + 1,
                  NS_ERROR_OUT_OF_MEMORY);
-  if (aIsMessage) {
+  if (aWSFrameType == eUTF8MessageFrame) {
     // without the START_BYTE_OF_MESSAGE and END_BYTE_OF_MESSAGE bytes
     mOutgoingBufferedAmount += aBuffer->Length() - 2;
+  } else if (aWSFrameType == eCloseFrame) {
+    mPostedCloseFrame = PR_TRUE;
   }
 
   if (sizeBefore == 0) {
     mBytesAlreadySentOfFirstOutString = 0;
     rv = mSocketOutput->AsyncWait(this, 0, 0, gWebSocketThread);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
@@ -747,17 +772,17 @@ nsWebSocketEstablishedConnection::PostMe
   *end = static_cast<char>(END_BYTE_OF_MESSAGE);
 
   outLen += 2;
 
   buf->SetLength(outLen);
   ENSURE_TRUE_AND_FAIL_IF_FAILED(buf->Length() == static_cast<PRUint32>(outLen),
                                  NS_ERROR_UNEXPECTED);
 
-  rv = PostData(buf.forget(), PR_TRUE);
+  rv = PostData(buf.forget(), eUTF8MessageFrame);
   ENSURE_SUCCESS_AND_FAIL_IF_FAILED(rv, rv);
 
   return NS_OK;
 }
 
 IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_BEGIN(DoInitialRequest)
 {
   nsresult rv;
@@ -868,17 +893,17 @@ IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_BEGI
     headersToSend.RemoveElementAt(headerPosToSendNow);
   }
 
   buf->AppendLiteral("\r\n");
   buf->Append(key_3);
 
   mStatus = CONN_SENDING_INITIAL_REQUEST;
 
-  rv = PostData(buf.forget(), PR_FALSE);
+  rv = PostData(buf.forget(), eConnectFrame);
   CHECK_SUCCESS_AND_FAIL_IF_FAILED(rv);
 }
 IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_END
 
 static
 nsresult
 GetHttpResponseCode(const nsCString& aLine, PRUint32 aLen,
                     PRUint32 *aStatusCode, PRUint32 *aLineLen)
@@ -1450,21 +1475,21 @@ nsWebSocketEstablishedConnection::Reset(
   if (mSocketTransport) {
     mSocketTransport->Close(NS_OK);
     mSocketTransport = nsnull;
   }
   mSocketInput = nsnull;
   mSocketOutput = nsnull;
 
   while (mOutgoingMessages.GetSize() != 0) {
-    delete static_cast<nsCString*>(mOutgoingMessages.PopFront());
+    delete static_cast<nsWSFrame*>(mOutgoingMessages.PopFront());
   }
 
   while (mReceivedMessages.GetSize() != 0) {
-    delete static_cast<nsString*>(mReceivedMessages.PopFront());
+    delete static_cast<nsCString*>(mReceivedMessages.PopFront());
   }
 
   mBytesAlreadySentOfFirstOutString = 0;
   mBytesInBuffer = 0;
 
   return NS_OK;
 }
 
@@ -1680,17 +1705,17 @@ nsWebSocketEstablishedConnection::DoConn
   // Proxy Authorization
   rv = AddAuthorizationHeaders(*buf, PR_TRUE);
   ENSURE_SUCCESS_AND_FAIL_IF_FAILED(rv, rv);
 
   buf->AppendLiteral("\r\n");
 
   mStatus = CONN_CONNECTING_TO_HTTP_PROXY;
 
-  rv = PostData(buf.forget(), PR_FALSE);
+  rv = PostData(buf.forget(), eConnectFrame);
   ENSURE_SUCCESS_AND_FAIL_IF_FAILED(rv, rv);
 
   return NS_OK;
 }
 
 IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_BEGIN(AddWSConnecting)
 {
 #ifdef DEBUG
@@ -1940,16 +1965,20 @@ nsWebSocketEstablishedConnection::PrintE
 
   return NS_OK;
 }
 
 IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_BEGIN(Close)
 {
   nsresult rv;
 
+  // Disconnect() can release this object, so we keep a
+  // reference until the end of the method
+  nsRefPtr<nsWebSocketEstablishedConnection> kungfuDeathGrip = this;
+
   if (mOwner->mReadyState == nsIWebSocket::CONNECTING) {
     // we must not convey any failure information to scripts, so we just
     // disconnect and maintain the owner WebSocket object in the CONNECTING
     // state.
     Disconnect();
     return;
   }
 
@@ -1982,33 +2011,35 @@ IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_BEGI
     closeFrame->SetLength(2);
     if (closeFrame->Length() != 2) {
       return;
     }
 
     closeFrame->SetCharAt(START_BYTE_OF_CLOSE_FRAME, 0);
     closeFrame->SetCharAt(END_BYTE_OF_CLOSE_FRAME, 1);
 
-    rv = PostData(closeFrame.forget(), PR_FALSE);
+    rv = PostData(closeFrame.forget(), eCloseFrame);
     if (NS_FAILED(rv)) {
       NS_WARNING("Failed to post the close frame");
       return;
     }
-
-    mPostedCloseFrame = PR_TRUE;
   } else {
     // Probably failed to send the close frame. Just disconnect.
     Disconnect();
   }
 }
 IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_END
 
 void
 nsWebSocketEstablishedConnection::ForceClose()
 {
+  // Disconnect() can release this object, so we keep a
+  // reference until the end of the method
+  nsRefPtr<nsWebSocketEstablishedConnection> kungfuDeathGrip = this;
+
   if (mOwner->mReadyState == nsIWebSocket::CONNECTING) {
     // we must not convey any failure information to scripts, so we just
     // disconnect and maintain the owner WebSocket object in the CONNECTING
     // state.
     Disconnect();
     return;
   }
   mOwner->SetReadyState(nsIWebSocket::CLOSING);
@@ -2056,16 +2087,22 @@ nsWebSocketEstablishedConnection::Discon
 
   {
     MutexAutoLock lockDisconnect(mLockDisconnect);
 
     if (!mOwner) {
       return NS_OK;
     }
 
+    // If mOwner is deleted when calling mOwner->DontKeepAliveAnyMore()
+    // then this method can be called again, and we will get a deadlock.
+    nsRefPtr<nsWebSocket> kungfuDeathGrip = mOwner;
+
+    mOwner->DontKeepAliveAnyMore();
+
     RemoveWSConnecting();
 
     mStatus = CONN_CLOSED;
     mOwner = nsnull;
 
     if (mAuthProvider) {
       mAuthProvider->Disconnect(NS_ERROR_ABORT);
       mAuthProvider = nsnull;
@@ -2106,21 +2143,21 @@ nsWebSocketEstablishedConnection::Discon
     }
     if (mSocketTransport) {
       mSocketTransport->Close(NS_OK);
       mSocketTransport = nsnull;
     }
     mProxyInfo = nsnull;
 
     while (mOutgoingMessages.GetSize() != 0) {
-      delete static_cast<nsCString*>(mOutgoingMessages.PopFront());
+      delete static_cast<nsWSFrame*>(mOutgoingMessages.PopFront());
     }
 
     while (mReceivedMessages.GetSize() != 0) {
-      delete static_cast<nsString*>(mReceivedMessages.PopFront());
+      delete static_cast<nsCString*>(mReceivedMessages.PopFront());
     }
 
     // Remove ourselves from the document's load group. nsIRequest expects
     // this be done asynchronously.
     nsCOMPtr<nsIRunnable> event =
       NS_NewRunnableMethod(this, &nsWebSocketEstablishedConnection::
                                   RemoveFromLoadGroup);
     if (event) {
@@ -2601,23 +2638,23 @@ nsWebSocketEstablishedConnection::OnInpu
       ENSURE_SUCCESS_AND_FAIL_IF_FAILED(rv, rv);
 
       // check if the stream has been closed
       if (read == 0) {
         // If we are asking for credentials then the old connection has been
         // closed. In this case we have to reset the WebSocket, not Close it.
         if (mStatus != CONN_RETRYING_TO_AUTHENTICATE) {
           mStatus = CONN_CLOSED;
+          mFailureStatus = NS_BASE_STREAM_CLOSED;
           if (mStatus < CONN_CONNECTED_AND_READY) {
             FailConnection();
           } else {
             Close();
           }
         }
-        mFailureStatus = NS_BASE_STREAM_CLOSED;
         return NS_BASE_STREAM_CLOSED;
       }
 
       PRUint32 start = mBytesInBuffer;
       mBytesInBuffer += read;
       rv = HandleNewInputString(start);
       ENSURE_SUCCESS_AND_FAIL_IF_FAILED(rv, rv);
     }
@@ -2654,23 +2691,24 @@ nsWebSocketEstablishedConnection::OnOutp
 
       while (PR_TRUE) {
         if (mOutgoingMessages.GetSize() == 0) {
           break;
         }
 
         // send what we can of the 1st string
 
-        nsCString *strToSend =
-          static_cast<nsCString*>(mOutgoingMessages.PeekFront());
+        nsWSFrame *frameToSend =
+          static_cast<nsWSFrame*>(mOutgoingMessages.PeekFront());
+        nsCString *strToSend = frameToSend->mData;
         PRUint32 sizeToSend =
           strToSend->Length() - mBytesAlreadySentOfFirstOutString;
         PRBool currentStrHasStartFrameByte =
           (mBytesAlreadySentOfFirstOutString == 0);
-        PRBool strIsMessage = (mStatus >= CONN_CONNECTED_AND_READY);
+        PRBool strIsMessage = (frameToSend->mType == eUTF8MessageFrame);
 
         if (sizeToSend != 0) {
           PRUint32 written;
           rv = aStream->Write(strToSend->get() + mBytesAlreadySentOfFirstOutString,
                               sizeToSend, &written);
           if (rv == NS_BASE_STREAM_WOULD_BLOCK) {
             break;
           }
@@ -2686,22 +2724,22 @@ nsWebSocketEstablishedConnection::OnOutp
             return ResolveNextProxyAndConnect();
           }
 
           mFailureStatus = rv;
           ENSURE_SUCCESS_AND_FAIL_IF_FAILED(rv, rv);
 
           if (written == 0) {
             mStatus = CONN_CLOSED;
+            mFailureStatus = NS_BASE_STREAM_CLOSED;
             if (mStatus < CONN_CONNECTED_AND_READY) {
               FailConnection();
             } else {
               Close();
             }
-            mFailureStatus = NS_BASE_STREAM_CLOSED;
             return NS_BASE_STREAM_CLOSED;
           }
 
           if (strIsMessage) {
             PRBool currentStrHasEndFrameByte =
               (mBytesAlreadySentOfFirstOutString + written ==
                strToSend->Length());
 
@@ -2726,17 +2764,17 @@ nsWebSocketEstablishedConnection::OnOutp
 
         sizeToSend = strToSend->Length() - mBytesAlreadySentOfFirstOutString;
         if (sizeToSend != 0) { // if different, we try sending what remain after
           break;
         }
 
         // ok, send the next string
         mOutgoingMessages.PopFront();
-        delete strToSend;
+        delete frameToSend;
         mBytesAlreadySentOfFirstOutString = 0;
       }
 
       if (mOutgoingMessages.GetSize() != 0) {
         rv = mSocketOutput->AsyncWait(this, 0, 0, gWebSocketThread);
         ENSURE_SUCCESS_AND_FAIL_IF_FAILED(rv, rv);
       } else {
         if (mStatus == CONN_SENDING_ACK_CLOSE_FRAME &&
@@ -2798,23 +2836,29 @@ nsWebSocketEstablishedConnection::GetInt
 
   return NS_ERROR_UNEXPECTED;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsWebSocket
 ////////////////////////////////////////////////////////////////////////////////
 
-nsWebSocket::nsWebSocket() : mReadyState(nsIWebSocket::CONNECTING),
+nsWebSocket::nsWebSocket() : mHasStrongEventListeners(PR_FALSE),
+                             mCheckThereAreStrongEventListeners(PR_TRUE),
+                             mReadyState(nsIWebSocket::CONNECTING),
                              mOutgoingBufferedAmount(0)
 {
 }
 
 nsWebSocket::~nsWebSocket()
 {
+  if (mConnection) {
+    mConnection->Disconnect();
+    mConnection = nsnull;
+  }
   if (mListenerManager) {
     mListenerManager->Disconnect();
     mListenerManager = nsnull;
   }
 }
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsWebSocket)
 
@@ -2827,26 +2871,26 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mPrincipal)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mURI)
   NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mConnection");
   cb.NoteXPCOMChild(static_cast<nsIInterfaceRequestor*>(tmp->mConnection));
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsWebSocket,
                                                 nsDOMEventTargetWrapperCache)
+  if (tmp->mConnection) {
+    tmp->mConnection->Disconnect();
+    tmp->mConnection = nsnull;
+  }
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnOpenListener)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnMessageListener)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnCloseListener)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnErrorListener)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mPrincipal)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mURI)
-  if (tmp->mConnection) {
-    tmp->mConnection->Disconnect();
-    tmp->mConnection = nsnull;
-  }
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 DOMCI_DATA(WebSocket, nsWebSocket)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsWebSocket)
   NS_INTERFACE_MAP_ENTRY(nsIWebSocket)
   NS_INTERFACE_MAP_ENTRY(nsIJSNativeInitializer)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(WebSocket)
@@ -2950,17 +2994,19 @@ class nsWSCloseEvent : public nsRunnable
 public:
   nsWSCloseEvent(nsWebSocket *aWebSocket, PRBool aWasClean)
     : mWebSocket(aWebSocket),
       mWasClean(aWasClean)
   {}
 
   NS_IMETHOD Run()
   {
-    return mWebSocket->CreateAndDispatchCloseEvent(mWasClean);
+    nsresult rv = mWebSocket->CreateAndDispatchCloseEvent(mWasClean);
+    mWebSocket->UpdateMustKeepAlive();
+    return rv;
   }
 
 private:
   nsRefPtr<nsWebSocket> mWebSocket;
   PRBool mWasClean;
 };
 
 nsresult
@@ -3068,16 +3114,17 @@ nsWebSocket::SetReadyState(PRUint16 aNew
     NS_ASSERTION(mReadyState == nsIWebSocket::CONNECTING,
                  "unexpected readyState transition");
     mReadyState = aNewReadyState;
 
     rv = CreateAndDispatchSimpleEvent(NS_LITERAL_STRING("open"));
     if (NS_FAILED(rv)) {
       NS_WARNING("Failed to dispatch the open event");
     }
+    UpdateMustKeepAlive();
     return;
   }
 
   if (aNewReadyState == nsIWebSocket::CLOSING) {
     NS_ASSERTION((mReadyState == nsIWebSocket::CONNECTING) ||
                  (mReadyState == nsIWebSocket::OPEN),
                  "unexpected readyState transition");
     mReadyState = aNewReadyState;
@@ -3094,16 +3141,17 @@ nsWebSocket::SetReadyState(PRUint16 aNew
       new nsWSCloseEvent(this, mConnection->ClosedCleanly());
 
     mOutgoingBufferedAmount += mConnection->GetOutgoingBufferedAmount();
     mConnection = nsnull; // this is no longer necessary
 
     rv = NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
     if (NS_FAILED(rv)) {
       NS_WARNING("Failed to dispatch the close event");
+      UpdateMustKeepAlive();
     }
   }
 }
 
 nsresult
 nsWebSocket::ParseURL(const nsString& aURL)
 {
   nsresult rv;
@@ -3206,16 +3254,104 @@ nsWebSocket::SetProtocol(const nsString&
     }
   }
 
   CopyUTF16toUTF8(aProtocol, mProtocol);
   return NS_OK;
 }
 
 //-----------------------------------------------------------------------------
+// Methods that keep alive the WebSocket object when there are
+// onopen/onmessage event listeners.
+//-----------------------------------------------------------------------------
+
+void
+nsWebSocket::UpdateMustKeepAlive()
+{
+  if (!mCheckThereAreStrongEventListeners) {
+    return;
+  }
+
+  if (mHasStrongEventListeners) {
+    if (!mListenerManager ||
+        ((mReadyState != nsIWebSocket::CONNECTING ||
+          !mListenerManager->HasListenersFor(NS_LITERAL_STRING("open"))) &&
+         (mReadyState == nsIWebSocket::CLOSED ||
+          !mListenerManager->HasListenersFor(NS_LITERAL_STRING("message"))))) {
+      mHasStrongEventListeners = PR_FALSE;
+      static_cast<nsPIDOMEventTarget*>(this)->Release();
+    }
+  } else {
+    if ((mReadyState == nsIWebSocket::CONNECTING && mListenerManager &&
+         mListenerManager->HasListenersFor(NS_LITERAL_STRING("open"))) ||
+        (mReadyState != nsIWebSocket::CLOSED && mListenerManager &&
+         mListenerManager->HasListenersFor(NS_LITERAL_STRING("message")))) {
+      mHasStrongEventListeners = PR_TRUE;
+      static_cast<nsPIDOMEventTarget*>(this)->AddRef();
+    }
+  }
+}
+
+void
+nsWebSocket::DontKeepAliveAnyMore()
+{
+  if (mHasStrongEventListeners) {
+    mCheckThereAreStrongEventListeners = PR_FALSE;
+    mHasStrongEventListeners = PR_FALSE;
+    static_cast<nsPIDOMEventTarget*>(this)->Release();
+  }
+}
+
+NS_IMETHODIMP
+nsWebSocket::AddEventListener(const nsAString& aType,
+                              nsIDOMEventListener* aListener,
+                              PRBool aUseCapture)
+{
+  nsresult rv = nsDOMEventTargetHelper::AddEventListener(aType,
+                                                         aListener,
+                                                         aUseCapture);
+  if (NS_SUCCEEDED(rv)) {
+    UpdateMustKeepAlive();
+  }
+  return rv;
+}
+
+NS_IMETHODIMP
+nsWebSocket::RemoveEventListener(const nsAString& aType,
+                                 nsIDOMEventListener* aListener,
+                                 PRBool aUseCapture)
+{
+  nsresult rv = nsDOMEventTargetHelper::RemoveEventListener(aType,
+                                                            aListener,
+                                                            aUseCapture);
+  if (NS_SUCCEEDED(rv)) {
+    UpdateMustKeepAlive();
+  }
+  return rv;
+}
+
+NS_IMETHODIMP
+nsWebSocket::AddEventListener(const nsAString& aType,
+                              nsIDOMEventListener *aListener,
+                              PRBool aUseCapture,
+                              PRBool aWantsUntrusted,
+                              PRUint8 optional_argc)
+{
+  nsresult rv = nsDOMEventTargetHelper::AddEventListener(aType,
+                                                         aListener,
+                                                         aUseCapture,
+                                                         aWantsUntrusted,
+                                                         optional_argc);
+  if (NS_SUCCEEDED(rv)) {
+    UpdateMustKeepAlive();
+  }
+  return rv;
+}
+
+//-----------------------------------------------------------------------------
 // nsWebSocket::nsIWebSocket methods:
 //-----------------------------------------------------------------------------
 
 NS_IMETHODIMP
 nsWebSocket::GetUrl(nsAString& aURL)
 {
   aURL = mOriginalURL;
   return NS_OK;
@@ -3298,16 +3434,20 @@ NS_IMETHODIMP
 nsWebSocket::Close()
 {
   if (mReadyState == nsIWebSocket::CLOSING ||
       mReadyState == nsIWebSocket::CLOSED) {
     return NS_OK;
   }
 
   if (mReadyState == nsIWebSocket::CONNECTING) {
+    // FailConnection() can release the object if there are no strong event
+    // listeners, so we keep a reference before calling it
+    nsRefPtr<nsWebSocket> kungfuDeathGrip = this;
+
     mConnection->FailConnection();
 
     // We need to set the readyState here because mConnection would set it
     // only if first connected. Also, let the two readyState changes here
     // for future extensions (for instance an onreadystatechange event)
     SetReadyState(nsIWebSocket::CLOSING);
     SetReadyState(nsIWebSocket::CLOSED);
     return NS_OK;
--- a/content/base/src/nsWebSocket.h
+++ b/content/base/src/nsWebSocket.h
@@ -81,39 +81,66 @@ public:
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsWebSocket,
                                            nsDOMEventTargetWrapperCache)
   NS_DECL_NSIWEBSOCKET
 
   // nsIJSNativeInitializer
   NS_IMETHOD Initialize(nsISupports* aOwner, JSContext* aContext,
                         JSObject* aObject, PRUint32 aArgc, jsval* aArgv);
 
+  // nsIDOMEventTarget
+  NS_IMETHOD AddEventListener(const nsAString& aType,
+                              nsIDOMEventListener* aListener,
+                              PRBool aUseCapture);
+  NS_IMETHOD RemoveEventListener(const nsAString& aType,
+                                 nsIDOMEventListener* aListener,
+                                 PRBool aUseCapture);
+
+  // nsIDOMNSEventTarget
+  NS_IMETHOD AddEventListener(const nsAString& aType,
+                              nsIDOMEventListener *aListener,
+                              PRBool aUseCapture,
+                              PRBool aWantsUntrusted,
+                              PRUint8 optional_argc);
+
   static void ReleaseGlobals();
 
 protected:
   nsresult ParseURL(const nsString& aURL);
   nsresult SetProtocol(const nsString& aProtocol);
   nsresult EstablishConnection();
 
   nsresult CreateAndDispatchSimpleEvent(const nsString& aName);
   nsresult CreateAndDispatchMessageEvent(nsCString *aData);
   nsresult CreateAndDispatchCloseEvent(PRBool aWasClean);
 
   // called from mConnection accordingly to the situation
   void SetReadyState(PRUint16 aNewReadyState);
 
+  // if there are onopen or onmessage event listeners ("strong event listeners")
+  // then this method keeps the object alive when js doesn't have strong
+  // references to it.
+  void UpdateMustKeepAlive();
+  // Releases, if necessary, the strong event listeners. ATTENTION, when calling
+  // this method the object can be released (and possibly collected).
+  void DontKeepAliveAnyMore();
+
   nsRefPtr<nsDOMEventListenerWrapper> mOnOpenListener;
   nsRefPtr<nsDOMEventListenerWrapper> mOnErrorListener;
   nsRefPtr<nsDOMEventListenerWrapper> mOnMessageListener;
   nsRefPtr<nsDOMEventListenerWrapper> mOnCloseListener;
 
   // related to the WebSocket constructor steps
   nsString mOriginalURL;
   PRPackedBool mSecure; // if true it is using SSL and the wss scheme,
                         // otherwise it is using the ws scheme with no SSL
+
+  PRPackedBool mHasStrongEventListeners;
+  PRPackedBool mCheckThereAreStrongEventListeners;
+
   nsCString mAsciiHost;  // hostname
   PRUint32  mPort;
   nsCString mResource; // [filepath[?query]]
   nsCString mOrigin;
   nsCOMPtr<nsIURI> mURI;
   nsCString mProtocol;
 
   PRUint16 mReadyState;
--- a/content/base/src/nsXHTMLContentSerializer.cpp
+++ b/content/base/src/nsXHTMLContentSerializer.cpp
@@ -96,16 +96,18 @@ nsXHTMLContentSerializer::~nsXHTMLConten
   NS_ASSERTION(mOLStateStack.IsEmpty(), "Expected OL State stack to be empty");
 }
 
 NS_IMETHODIMP
 nsXHTMLContentSerializer::Init(PRUint32 aFlags, PRUint32 aWrapColumn,
                               const char* aCharSet, PRBool aIsCopying,
                               PRBool aRewriteEncodingDeclaration)
 {
+  mInBody = 0;
+
   // The previous version of the HTML serializer did implicit wrapping
   // when there is no flags, so we keep wrapping in order to keep
   // compatibility with the existing calling code
   // XXXLJ perhaps should we remove this default settings later ?
   if (aFlags & nsIDocumentEncoder::OutputFormatted ) {
       aFlags = aFlags | nsIDocumentEncoder::OutputWrap;
   }
 
--- a/content/base/src/nsXMLContentSerializer.cpp
+++ b/content/base/src/nsXMLContentSerializer.cpp
@@ -106,16 +106,25 @@ nsXMLContentSerializer::~nsXMLContentSer
 
 NS_IMPL_ISUPPORTS1(nsXMLContentSerializer, nsIContentSerializer)
 
 NS_IMETHODIMP 
 nsXMLContentSerializer::Init(PRUint32 aFlags, PRUint32 aWrapColumn,
                              const char* aCharSet, PRBool aIsCopying,
                              PRBool aRewriteEncodingDeclaration)
 {
+  mPrefixIndex = 0;
+  mColPos = 0;
+  mIndentOverflow = 0;
+  mIsIndentationAddedOnCurrentLine = PR_FALSE;
+  mInAttribute = PR_FALSE;
+  mAddNewlineForRootNode = PR_FALSE;
+  mAddSpace = PR_FALSE;
+  mMayIgnoreLineBreakSequence = PR_FALSE;
+
   mCharset = aCharSet;
   mFlags = aFlags;
 
   // Set the line break character:
   if ((mFlags & nsIDocumentEncoder::OutputCRLineBreak)
       && (mFlags & nsIDocumentEncoder::OutputLFLineBreak)) { // Windows
     mLineBreak.AssignLiteral("\r\n");
   }
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -389,16 +389,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug562652.html \
 		test_bug562137.html \
 		file_bug562137.txt \
 		test_bug548193.html \
 		file_bug548193.sjs \
 		test_html_colors_quirks.html \
 		test_html_colors_standards.html \
 		test_bug571390.xul \
+		test_bug300992.html \
 		test_websocket_hello.html \
 		file_websocket_hello_wsh.py \
 		test_ws_basic_tests.html \
 		file_ws_basic_tests_wsh.py \
 		test_websocket.html \
 		file_websocket_wsh.py \
 		file_websocket_http_resource.txt \
 		$(NULL)
--- a/content/base/test/file_websocket_wsh.py
+++ b/content/base/test/file_websocket_wsh.py
@@ -1,67 +1,90 @@
 from mod_pywebsocket import msgutil
 
 import time
 import sys
 
 # see the list of tests in test_websocket.html
 
 def web_socket_do_extra_handshake(request):
-  if request.ws_protocol == "test 6":
-    sys.exit(0)
-  elif request.ws_protocol == "test 19":
-    time.sleep(180)
-    pass
-  elif request.ws_protocol == "test 8":
+  if request.ws_protocol == "test 2.1":
     time.sleep(5)
     pass
   elif request.ws_protocol == "test 9":
     time.sleep(5)
     pass
-  elif request.ws_protocol == "test 10.1":
+  elif request.ws_protocol == "test 10":
     time.sleep(5)
     pass
+  elif request.ws_protocol == "test 19":
+    raise ValueError('Aborting (test 19)')
+  elif request.ws_protocol == "test 20" or request.ws_protocol == "test 17":
+    time.sleep(10)
+    pass
+  elif request.ws_protocol == "test 22":
+    time.sleep(60)
+    pass
   else:
     pass
 
 def web_socket_transfer_data(request):
-  if request.ws_protocol == "test 9":
+  if request.ws_protocol == "test 2.1" or request.ws_protocol == "test 2.2":
+    msgutil.close_connection(request)
+  elif request.ws_protocol == "test 6":
+    resp = "wrong message"
+    if msgutil.receive_message(request) == "1":
+      resp = "2"
+    msgutil.send_message(request, resp.decode('utf-8'))
+    resp = "wrong message"
+    if msgutil.receive_message(request) == "3":
+      resp = "4"
+    msgutil.send_message(request, resp.decode('utf-8'))
+    resp = "wrong message"
+    if msgutil.receive_message(request) == "5":
+      resp = "あいうえお"
+    msgutil.send_message(request, resp.decode('utf-8'))
+  elif request.ws_protocol == "test 7":
+    try:
+      while not request.client_terminated:
+        msgutil.receive_message(request)
+    except msgutil.ConnectionTerminatedException, e:
+      pass
+    msgutil.send_message(request, "server data")
+    msgutil.send_message(request, "server data")
+    msgutil.send_message(request, "server data")
+    msgutil.send_message(request, "server data")
+    msgutil.send_message(request, "server data")
+    time.sleep(30)
+    msgutil.close_connection(request, True)
+  elif request.ws_protocol == "test 10":
     msgutil.close_connection(request)
   elif request.ws_protocol == "test 11":
     resp = "wrong message"
     if msgutil.receive_message(request) == "client data":
       resp = "server data"
     msgutil.send_message(request, resp.decode('utf-8'))
   elif request.ws_protocol == "test 13":
     # first one binary message containing the byte 0x61 ('a')
     request.connection.write('\xff\x01\x61')
     # after a bad utf8 message
     request.connection.write('\x01\x61\xff')
     msgutil.close_connection(request)
   elif request.ws_protocol == "test 14":
     request.connection.write('\xff\x00')
     msgutil.send_message(request, "server data")
   elif request.ws_protocol == "test 15":
-    sys.exit (0)
-  elif request.ws_protocol == "test 17":
-    while not request.client_terminated:
-      msgutil.send_message(request, "server data")
-      time.sleep(1)
-    msgutil.send_message(request, "server data")
-    sys.exit(0)
-  elif request.ws_protocol == "test 18":
+    msgutil.close_connection(request, True)
+    return
+  elif request.ws_protocol == "test 17" or request.ws_protocol == "test 21":
+    time.sleep(5)
     resp = "wrong message"
-    if msgutil.receive_message(request) == "1":
-      resp = "2"
+    if msgutil.receive_message(request) == "client data":
+      resp = "server data"
     msgutil.send_message(request, resp.decode('utf-8'))
-    resp = "wrong message"
-    if msgutil.receive_message(request) == "3":
-      resp = "4"
-    msgutil.send_message(request, resp.decode('utf-8'))
-    resp = "wrong message"
-    if msgutil.receive_message(request) == "5":
-      resp = "あいうえお"
-    msgutil.send_message(request, resp.decode('utf-8'))
-  elif request.ws_protocol == "test 10.1" or request.ws_protocol == "test 10.2":
+    time.sleep(5)
+    msgutil.close_connection(request)
+    time.sleep(5)
+  elif request.ws_protocol == "test 20":
+    msgutil.send_message(request, "server data")
     msgutil.close_connection(request)
   while not request.client_terminated:
     msgutil.receive_message(request)
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug300992.html
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=300992
+-->
+<head>
+  <title>Test for Bug 300992</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=300992">Mozilla Bug 300992</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 300992 **/
+SimpleTest.waitForExplicitFinish();
+
+var i = 0;
+var states = ['loading',
+  'interactive1', 'interactive2',
+  'complete1', 'complete2'];
+
+is(document.readyState, states[i++], 'initial readyState');
+document.onreadystatechange = function (event) {
+  is(document.readyState + '1', states[i++], 'readystatechange event "on" handler');
+};
+document.addEventListener('readystatechange', function(event) {
+  is(document.readyState + '2', states[i++], 'readystatechange event document listener');
+}, false);
+window.addEventListener('readystatechange', function(event) {
+  ok(false, 'window listener', 'readystatechange event should not bubble to window');
+}, false);
+setTimeout(function() {
+  is(i, states.length, 'readystatechange event count');
+  SimpleTest.finish();
+}, 1000);
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/base/test/test_websocket.html
+++ b/content/base/test/test_websocket.html
@@ -13,81 +13,74 @@
 <div id="content">
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /*
  * tests:
  *  1. client tries to connect to a http scheme location;
- *  2. client tries to connect to an http resource;
+ *  2. assure serialization of the connections;
  *  3. client tries to connect to an non-existent ws server;
  *  4. client tries to connect using a relative url;
  *  5. client uses an invalid protocol value;
- *  6. server closes the tcp connection before establishing the ws connection;
- *  7. client calls close() and the server sends the close frame in
+ *  6. counter and encoding check;
+ *  7. client calls close() and the server keeps sending messages and it doesn't
+ *     send the close frame;
+ *  8. client calls close() and the server sends the close frame in
  *     acknowledgement;
- *  8. client closes the connection before the ws connection is established;
- *  9. client sends a message before the ws connection is established;
- * 10. assure serialization of the connections;
+ *  9. client closes the connection before the ws connection is established;
+ * 10. client sends a message before the ws connection is established;
  * 11. a simple hello echo;
  * 12. client sends a message with bad bytes;
  * 13. server sends an invalid message;
  * 14. server sends the close frame, it doesn't close the tcp connection and
  *     it keeps sending normal ws messages;
  * 15. server closes the tcp connection, but it doesn't send the close frame;
  * 16. client calls close() and tries to send a message;
- * 17. client calls close() and the server keeps sending messages and it doesn't
- *     send the close frame;
- * 18. counter and encoding check;
- * 19. server takes too long to establish the ws connection;
+ * 17. see bug 572975 - all event listeners set
+ * 18. client tries to connect to an http resource;
+ * 19. server closes the tcp connection before establishing the ws connection;
+ * 20. see bug 572975 - only on error and onclose event listeners set
+ * 21. see bug 572975 - same as test 17, but delete strong event listeners when
+ *     receiving the message event;
+ * 22. server takes too long to establish the ws connection;
  */
 
 var first_test = 1;
-var last_test = 19;
+var last_test = 22;
 
-var current_test = 1;
+var current_test = first_test;
 
 var timeoutToAbortTest = 60000;
+var timeoutToOpenWS = 25000;
 var all_ws = [];
 
 function shouldNotOpen(e)
 {
   var ws = e.target;
   ok(false, "onopen shouldn't be called on test " + ws._testNumber + "!");
-  if (ws._timeoutToSucceed != undefined) {
-    clearTimeout(ws._timeoutToSucceed);
-  }
 }
 
 function shouldNotReceiveCloseEvent(e)
 {
   var ws = e.target;
   ok(false, "onclose shouldn't be called on test " + ws._testNumber + "!");
-  if (ws._timeoutToSucceed != undefined) {
-    clearTimeout(ws._timeoutToSucceed);
-  }
 }
 
 function shouldCloseCleanly(e)
 {
   var ws = e.target;
-  //ok(e.wasClean, "the ws connection in test " + ws._testNumber + " should be closed cleanly");
-  if (ws._timeoutToSucceed != undefined) {
-    clearTimeout(ws._timeoutToSucceed);
-  }
+  ok(e.wasClean, "the ws connection in test " + ws._testNumber + " should be closed cleanly");
 }
 
 function shouldCloseNotCleanly(e)
 {
   var ws = e.target;
-  //ok(!e.wasClean, "the ws connection in test " + ws._testNumber + " shouldn't be closed cleanly");
-  if (ws._timeoutToSucceed != undefined) {
-    clearTimeout(ws._timeoutToSucceed);
-  }
+  ok(!e.wasClean, "the ws connection in test " + ws._testNumber + " shouldn't be closed cleanly");
 }
 
 function CreateTestWS(ws_location, ws_protocol)
 {
   var ws;
 
   try {
     if (ws_protocol == undefined) {
@@ -114,16 +107,30 @@ function CreateTestWS(ws_location, ws_pr
   finally {
     current_test++;
   }
 
   all_ws.push(ws);
   return ws;
 }
 
+function forcegc()
+{
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+  Components.utils.forceGC();
+  var wu =  window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
+                  .getInterface(Components.interfaces.nsIDOMWindowUtils);
+  wu.garbageCollect();
+  setTimeout(function()
+  {
+    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+    wu.garbageCollect();
+  }, 1);
+}
+
 function doTest(number)
 {
   if (doTest.timeoutId !== null) {
     clearTimeout(doTest.timeoutId);
     doTest.timeoutId = null;
   }
 
   if (number > last_test) {
@@ -158,40 +165,56 @@ function test1()
     ok(false, "test1 failed");
   }
   catch (e) {
     ok(true, "test1 failed");
   }
   doTest(2);
 }
 
+// this test expects that the serialization list to connect to the proxy
+// is empty
 function test2()
 {
-  var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket_http_resource.txt");
-  ws.onopen = shouldNotOpen;
-  ws.onclose = shouldNotReceiveCloseEvent;
-  doTest(3);
+  var ws1 = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 2.1");
+  current_test--; // CreateTestWS incremented this
+  var ws2 = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 2.2");
+
+  var ws2CanConnect = false;
+
+  // the server will delay ws1 for 5 seconds
+
+  ws1.onopen = function()
+  {
+    ws2CanConnect = true;
+  }
+
+  ws2.onopen = function()
+  {
+    ok(ws2CanConnect, "shouldn't connect yet in test 2!");
+    doTest(3);
+  }
 }
 
 function test3()
 {
   var ws = CreateTestWS("ws://this.websocket.server.probably.does.not.exist");
   ws.onopen = shouldNotOpen;
   ws.onclose = shouldNotReceiveCloseEvent;
   doTest(4);
 }
 
 function test4()
 {
   try {
     var ws = CreateTestWS("file_websocket");
-    ok(false, "test4 failed");
+    ok(false, "test 4 failed");
   }
   catch (e) {
-    ok(true, "test4 failed");
+    ok(true, "test 4 failed");
   }
   doTest(5);
 }
 
 function test5()
 {
   try {
     var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "");
@@ -209,84 +232,96 @@ function test5()
     ok(true, "couldn't accept any not printable ASCII character in the protocol parameter");
   }
   doTest(6);
 }
 
 function test6()
 {
   var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 6");
-  ws.onopen = shouldNotOpen;
-  ws.onclose = shouldNotReceiveCloseEvent;
-  doTest(7);
+  var counter = 1;
+  ws.onopen = function()
+  {
+    ws.send(counter);
+  }
+  ws.onmessage = function(e)
+  {
+    if (counter == 5) {
+      ok(e.data == "あいうえお");
+      ws.close();
+      doTest(7);
+    } else {
+      ok(e.data == counter+1, "bad counter");
+      counter += 2;
+      ws.send(counter);
+    }
+  }
+  ws.onclose = shouldCloseCleanly;
+  ws._receivedCloseEvent = false;
 }
 
 function test7()
 {
   var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 7");
   ws.onopen = function()
   {
     ws.close();
   }
   ws.onclose = function(e)
   {
-    shouldCloseCleanly(e);
+    shouldCloseNotCleanly(e);
     doTest(8);
   };
   ws._receivedCloseEvent = false;
 }
 
 function test8()
 {
   var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 8");
+  ws.onopen = function()
+  {
+    ws.close();
+  }
+  ws.onclose = function(e)
+  {
+    shouldCloseCleanly(e);
+    doTest(9);
+  };
+  ws._receivedCloseEvent = false;
+}
+
+function test9()
+{
+  var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 9");
   ws.onopen = shouldNotOpen;
   ws.onclose = function(e)
   {
     shouldCloseNotCleanly(e);
-    doTest(9);
+    doTest(10);
   };
 
   ws._receivedCloseEvent = false;
   ws.close();
 }
 
-function test9()
+function test10()
 {
-  var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 9");
+  var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 10");
   ws.onclose = shouldCloseCleanly;
   ws._receivedCloseEvent = false;
 
   try {
     ws.send("client data");
     ok(false, "Couldn't send data before connecting!");
   }
   catch (e) {
     ok(true, "Couldn't send data before connecting!");
   }
-  doTest(10);
-}
-
-function test10()
-{
-  var ws1 = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 10.1");
-  current_test--; // CreateTestWS incremented this
-  var ws2 = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 10.2");
-
-  var ws2CanConnect = false;
-
-  // the server will delay ws1 for 5 seconds
-
-  ws1.onopen = function()
+  ws.onopen = function()
   {
-    ws2CanConnect = true;
-  }
-
-  ws2.onopen = function()
-  {
-    ok(ws2CanConnect, "shouldn't connect yet in test 10!");
     doTest(11);
   }
 }
 
 function test11()
 {
   var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 11");
   ok(ws.readyState == 0, "bad readyState in test 11!");
@@ -331,18 +366,18 @@ function test12()
 function test13()
 {
   var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 13");
   ws._timesCalledOnError = 0;
   ws.onerror = function()
   {
     ws._timesCalledOnError++;
     if (ws._timesCalledOnError == 2) {
+      ok(true, "test 13 succeeded");
       doTest(14);
-      ok(true, "test13 succeeded");
     }
   }
   ws.onclose = shouldCloseCleanly;
   ws._receivedCloseEvent = false;
 }
 
 function test14()
 {
@@ -382,63 +417,158 @@ function test16()
   ws.onmessage = function()
   {
     ok(false, "shouldn't send message after calling close()");
   }
   ws.onclose = shouldCloseCleanly;
   ws._receivedCloseEvent = false;
 }
 
+var status_test17 = "not started";
+
+window._test17 = function()
+{
+  var local_ws = new WebSocket("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 17");
+
+  status_test17 = "started";
+
+  local_ws.onopen = function(e)
+  {
+    status_test17 = "opened";
+    e.target.send("client data");
+    forcegc();
+  };
+
+  local_ws.onerror = function()
+  {
+    ok(false, "onerror called on test " + e.target._testNumber + "!");
+  };
+
+  local_ws.onmessage = function(e)
+  {
+    ok(e.data == "server data", "Bad message in test 17");
+    status_test17 = "got message";
+    forcegc();
+  };
+
+  local_ws.onclose = function(e)
+  {
+    ok(status_test17 == "got message", "Didn't got message in test 17!");
+    shouldCloseCleanly(e);
+    status_test17 = "closed";
+    forcegc();
+    doTest(18);
+    forcegc();
+  };
+
+  local_ws = null;
+  window._test17 = null;
+  forcegc();
+}
+
 function test17()
 {
-  var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 17");
-  ws.onopen = function()
-  {
-    ws.close();
-  }
-  ws.onclose = function(e)
-  {
-    shouldCloseNotCleanly(e);
-    doTest(18);
-  };
-  ws._receivedCloseEvent = false;
+  window._test17();
 }
 
+// The tests that expects that their websockets neither open nor close MUST
+// be in the end of the tests, i.e. HERE, in order to prevent blocking the other
+// tests.
+
 function test18()
 {
-  var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 18");
-  var counter = 1;
-  ws.onopen = function()
-  {
-    ws.send(counter);
-  }
-  ws.onmessage = function(e)
-  {
-    if (counter == 5) {
-      ok(e.data == "あいうえお");
-      ws.close();
-      doTest(19);
-    } else {
-      ok(e.data == counter+1, "bad counter");
-      counter += 2;
-      ws.send(counter);
-    }
-  }
-  ws.onclose = shouldCloseCleanly;
-  ws._receivedCloseEvent = false;
+  var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket_http_resource.txt");
+  ws.onopen = shouldNotOpen;
+  ws.onclose = shouldNotReceiveCloseEvent;
+  doTest(19);
 }
 
 function test19()
 {
   var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 19");
   ws.onopen = shouldNotOpen;
   ws.onclose = shouldNotReceiveCloseEvent;
   doTest(20);
 }
 
+window._test20 = function()
+{
+  var local_ws = new WebSocket("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 20");
+
+  local_ws.onerror = function()
+  {
+    ok(false, "onerror called on test " + e.target._testNumber + "!");
+  };
+
+  local_ws.onclose = shouldNotReceiveCloseEvent;
+
+  local_ws = null;
+  window._test20 = null;
+  forcegc();
+}
+
+function test20()
+{
+  window._test20();
+  doTest(21);
+}
+
+var timeoutTest21;
+
+window._test21 = function()
+{
+  var local_ws = new WebSocket("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 21");
+
+  local_ws.onopen = function(e)
+  {
+    e.target.send("client data");
+    timeoutTest21 = setTimeout(function()
+    {
+      ok(false, "Didn't received message on test 21!");
+    }, 15000);
+    forcegc();
+    e.target.onopen = null;
+    forcegc();
+  };
+
+  local_ws.onerror = function()
+  {
+    ok(false, "onerror called on test " + e.target._testNumber + "!");
+  };
+
+  local_ws.onmessage = function(e)
+  {
+    clearTimeout(timeoutTest21);
+    ok(e.data == "server data", "Bad message in test 21");
+    forcegc();
+    e.target.onmessage = null;
+    forcegc();
+  };
+
+  local_ws.onclose = shouldNotReceiveCloseEvent;
+
+  local_ws = null;
+  window._test21 = null;
+  forcegc();
+}
+
+function test21()
+{
+  window._test21();
+  doTest(22);
+}
+
+function test22()
+{
+  var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test 22");
+  ws.onopen = shouldNotOpen;
+  ws.onclose = shouldNotReceiveCloseEvent;
+  doTest(23);
+}
+
 function finishWSTest()
 {
   for (i = 0; i < all_ws.length; ++i) {
     if (all_ws[i]._receivedCloseEvent === false) {
       ok(false, "didn't called close on test " + all_ws[i]._testNumber + "!");
     }
   }
   SimpleTest.finish();
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -618,17 +618,17 @@ protected:
     /**
      * Gets the pres shell from either the canvas element or the doc shell
      */
     nsIPresShell *GetPresShell() {
       nsCOMPtr<nsIContent> content =
         do_QueryInterface(static_cast<nsIDOMHTMLCanvasElement*>(mCanvasElement));
       if (content) {
         nsIDocument* ownerDoc = content->GetOwnerDoc();
-        return ownerDoc ? ownerDoc->GetPrimaryShell() : nsnull;
+        return ownerDoc ? ownerDoc->GetShell() : nsnull;
       }
       if (mDocShell) {
         nsCOMPtr<nsIPresShell> shell;
         mDocShell->GetPresShell(getter_AddRefs(shell));
         return shell.get();
       }
       return nsnull;
     }
@@ -854,17 +854,20 @@ nsCanvasRenderingContext2D::~nsCanvasRen
 void
 nsCanvasRenderingContext2D::Destroy()
 {
     ContentProcessParent* allocator = ContentProcessParent::GetSingleton(PR_FALSE);
     if (allocator && gfxSharedImageSurface::IsSharedImage(mSurface)) {
         Shmem &mem = static_cast<gfxSharedImageSurface*>(mSurface.get())->GetShmem();
         allocator->DeallocShmem(mem);
     }
-    if (mValid)
+
+    // only do this for non-docshell created contexts,
+    // since those are the ones that we created a surface for
+    if (mValid && !mDocShell)
         gCanvasMemoryUsed -= mWidth * mHeight * 4;
 
     mSurface = nsnull;
     mThebes = nsnull;
     mValid = PR_FALSE;
     mIsEntireFrameInvalid = PR_FALSE;
 }
 
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -57,19 +57,20 @@
 #include "nsContentUtils.h"
 #include "nsIURI.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIScriptError.h"
 #include "nsDOMPopStateEvent.h"
 
 static const char* const sEventNames[] = {
   "mousedown", "mouseup", "click", "dblclick", "mouseover",
-  "mouseout", "mousemove", "contextmenu", "keydown", "keyup", "keypress",
-  "focus", "blur", "load", "popstate", "beforeunload", "unload", "hashchange",
-  "abort", "error", "submit", "reset", "change", "select", "input", "text",
+  "mouseout", "MozMouseHittest", "mousemove", "contextmenu", "keydown", "keyup", "keypress",
+  "focus", "blur", "load", "popstate", "beforeunload", "unload",
+  "hashchange", "readystatechange", "abort", "error",
+  "submit", "reset", "change", "select", "input", "text",
   "compositionstart", "compositionend", "popupshowing", "popupshown",
   "popuphiding", "popuphidden", "close", "command", "broadcast", "commandupdate",
   "dragenter", "dragover", "dragexit", "dragdrop", "draggesture",
   "drag", "dragend", "dragstart", "dragleave", "drop", "resize",
   "scroll", "overflow", "underflow", "overflowchanged",
   "DOMSubtreeModified", "DOMNodeInserted", "DOMNodeRemoved", 
   "DOMNodeRemovedFromDocument", "DOMNodeInsertedIntoDocument",
   "DOMAttrModified", "DOMCharacterDataModified",
@@ -1071,16 +1072,18 @@ const char* nsDOMEvent::GetEventName(PRU
   case NS_MOUSE_CLICK:
     return sEventNames[eDOMEvents_click];
   case NS_MOUSE_DOUBLECLICK:
     return sEventNames[eDOMEvents_dblclick];
   case NS_MOUSE_ENTER_SYNTH:
     return sEventNames[eDOMEvents_mouseover];
   case NS_MOUSE_EXIT_SYNTH:
     return sEventNames[eDOMEvents_mouseout];
+  case NS_MOUSE_MOZHITTEST:
+    return sEventNames[eDOMEvents_MozMouseHittest];
   case NS_MOUSE_MOVE:
     return sEventNames[eDOMEvents_mousemove];
   case NS_KEY_UP:
     return sEventNames[eDOMEvents_keyup];
   case NS_KEY_DOWN:
     return sEventNames[eDOMEvents_keydown];
   case NS_KEY_PRESS:
     return sEventNames[eDOMEvents_keypress];
@@ -1099,16 +1102,18 @@ const char* nsDOMEvent::GetEventName(PRU
   case NS_POPSTATE:
     return sEventNames[eDOMEvents_popstate];
   case NS_BEFORE_PAGE_UNLOAD:
     return sEventNames[eDOMEvents_beforeunload];
   case NS_PAGE_UNLOAD:
     return sEventNames[eDOMEvents_unload];
   case NS_HASHCHANGE:
     return sEventNames[eDOMEvents_hashchange];
+  case NS_READYSTATECHANGE:
+    return sEventNames[eDOMEvents_readystatechange];
   case NS_IMAGE_ABORT:
     return sEventNames[eDOMEvents_abort];
   case NS_LOAD_ERROR:
     return sEventNames[eDOMEvents_error];
   case NS_FORM_SUBMIT:
     return sEventNames[eDOMEvents_submit];
   case NS_FORM_RESET:
     return sEventNames[eDOMEvents_reset];
--- a/content/events/src/nsDOMEvent.h
+++ b/content/events/src/nsDOMEvent.h
@@ -62,28 +62,30 @@ public:
   // Note: this enum must be kept in sync with sEventNames in nsDOMEvent.cpp
   enum nsDOMEvents {
     eDOMEvents_mousedown=0,
     eDOMEvents_mouseup,
     eDOMEvents_click,
     eDOMEvents_dblclick,
     eDOMEvents_mouseover,
     eDOMEvents_mouseout,
+    eDOMEvents_MozMouseHittest,
     eDOMEvents_mousemove,
     eDOMEvents_contextmenu,
     eDOMEvents_keydown,
     eDOMEvents_keyup,
     eDOMEvents_keypress,
     eDOMEvents_focus,
     eDOMEvents_blur,
     eDOMEvents_load,
     eDOMEvents_popstate,
     eDOMEvents_beforeunload,
     eDOMEvents_unload,
     eDOMEvents_hashchange,
+    eDOMEvents_readystatechange,
     eDOMEvents_abort,
     eDOMEvents_error,
     eDOMEvents_submit,
     eDOMEvents_reset,
     eDOMEvents_change,
     eDOMEvents_select,
     eDOMEvents_input,
     eDOMEvents_text,
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -1291,17 +1291,17 @@ nsEventListenerManager::DispatchEvent(ns
   nsCOMPtr<nsIDocument> document = targetNode->GetOwnerDoc();
 
   // Do nothing if the element does not belong to a document
   if (!document) {
     return NS_OK;
   }
 
   // Obtain a presentation shell
-  nsIPresShell *shell = document->GetPrimaryShell();
+  nsIPresShell *shell = document->GetShell();
   nsRefPtr<nsPresContext> context;
   if (shell) {
     context = shell->GetPresContext();
   }
 
   nsEventStatus status = nsEventStatus_eIgnore;
   nsresult rv =
     nsEventDispatcher::DispatchDOMEvent(targetNode, nsnull, aEvent,
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -1874,24 +1874,16 @@ nsEventStateManager::FillInEventFromGest
 }
 
 //
 // GenerateDragGesture
 //
 // If we're in the TRACKING state of the d&d gesture tracker, check the current position
 // of the mouse in relation to the old one. If we've moved a sufficient amount from
 // the mouse down, then fire off a drag gesture event.
-//
-// Note that when the mouse enters a new child window with its own view, the event's
-// coordinates will be in relation to the origin of the inner child window, which could
-// either be very different from that of the mouse coords of the mouse down and trigger
-// a drag too early, or very similar which might not trigger a drag.
-//
-// Do we need to do anything about this? Let's wait and see.
-//
 void
 nsEventStateManager::GenerateDragGesture(nsPresContext* aPresContext,
                                          nsMouseEvent *aEvent)
 {
   NS_ASSERTION(aPresContext, "This shouldn't happen.");
   if (IsTrackingDragGesture()) {
     mCurrentTarget = mGestureDownFrameOwner->GetPrimaryFrame();
 
@@ -2198,17 +2190,17 @@ nsEventStateManager::DoDefaultDragStart(
   // If a selection is being dragged, and no custom drag image was
   // set, get the selection so that the drag region can be created
   // from the selection area. If a custom image was set, it doesn't
   // matter what the selection is since the image will be used instead.
   nsISelection* selection = nsnull;
   if (aIsSelection && !dragImage) {
     nsIDocument* doc = aDragTarget->GetCurrentDoc();
     if (doc) {
-      nsIPresShell* presShell = doc->GetPrimaryShell();
+      nsIPresShell* presShell = doc->GetShell();
       if (presShell) {
         selection = presShell->GetCurrentSelection(
                       nsISelectionController::SELECTION_NORMAL);
       }
     }
   }
 
   nsCOMPtr<nsISupportsArray> transArray;
@@ -2278,17 +2270,17 @@ nsEventStateManager::GetMarkupDocumentVi
 
   nsCOMPtr<nsIDOMWindow> contentWindow;
   rootWindow->GetContent(getter_AddRefs(contentWindow));
   if(!contentWindow) return NS_ERROR_FAILURE;
 
   nsIDocument *doc = GetDocumentFromWindow(contentWindow);
   if(!doc) return NS_ERROR_FAILURE;
 
-  nsIPresShell *presShell = doc->GetPrimaryShell();
+  nsIPresShell *presShell = doc->GetShell();
   if(!presShell) return NS_ERROR_FAILURE;
   nsPresContext *presContext = presShell->GetPresContext();
   if(!presContext) return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsISupports> pcContainer = presContext->GetContainer();
   if(!pcContainer) return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIDocShell> docshell(do_QueryInterface(pcContainer));
@@ -3102,16 +3094,20 @@ nsEventStateManager::PostHandleEvent(nsP
         mCurrentTarget->GetContentForEvent(presContext, aEvent,
                                            getter_AddRefs(targetContent));
 
         nsCOMPtr<nsIWidget> widget = mCurrentTarget->GetWindow();
         nsDragEvent event(NS_IS_TRUSTED_EVENT(aEvent), NS_DRAGDROP_DRAGDROP, widget);
 
         nsMouseEvent* mouseEvent = static_cast<nsMouseEvent*>(aEvent);
         event.refPoint = mouseEvent->refPoint;
+        if (mouseEvent->widget) {
+          event.refPoint += mouseEvent->widget->WidgetToScreenOffset();
+        }
+        event.refPoint -= widget->WidgetToScreenOffset();
         event.isShift = mouseEvent->isShift;
         event.isControl = mouseEvent->isControl;
         event.isAlt = mouseEvent->isAlt;
         event.isMeta = mouseEvent->isMeta;
         event.inputSource = mouseEvent->inputSource;
 
         nsEventStatus status = nsEventStatus_eIgnore;
         nsCOMPtr<nsIPresShell> presShell = mPresContext->GetPresShell();
@@ -3565,17 +3561,17 @@ nsEventStateManager::NotifyMouseOver(nsG
   // Check to see if we're a subdocument and if so update the parent
   // document's ESM state to indicate that the mouse is over the
   // content associated with our subdocument.
   EnsureDocument(mPresContext);
   nsIDocument *parentDoc = mDocument->GetParentDocument();
   if (parentDoc) {
     nsIContent *docContent = parentDoc->FindContentForSubDocument(mDocument);
     if (docContent) {
-      nsIPresShell *parentShell = parentDoc->GetPrimaryShell();
+      nsIPresShell *parentShell = parentDoc->GetShell();
       if (parentShell) {
         nsEventStateManager* parentESM =
           static_cast<nsEventStateManager*>
                      (parentShell->GetPresContext()->EventStateManager());
         parentESM->NotifyMouseOver(aEvent, docContent);
       }
     }
   }
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -650,58 +650,60 @@ nsGenericHTMLElement::GetOffsetParent(ns
   return NS_OK;
 }
 
 nsresult
 nsGenericHTMLElement::GetInnerHTML(nsAString& aInnerHTML)
 {
   aInnerHTML.Truncate();
 
-  nsCOMPtr<nsIDocument> doc = GetOwnerDoc();
+  nsIDocument* doc = GetOwnerDoc();
   if (!doc) {
     return NS_OK; // We rely on the document for doing HTML conversion
   }
 
-  nsCOMPtr<nsIDOMNode> thisNode(do_QueryInterface(static_cast<nsIContent *>
-                                                             (this)));
   nsresult rv = NS_OK;
 
   nsAutoString contentType;
   if (IsInHTMLDocument()) {
     contentType.AssignLiteral("text/html");
   } else {
     doc->GetContentType(contentType);
   }
-  
-  nsCOMPtr<nsIDocumentEncoder> docEncoder;
-  docEncoder =
-    do_CreateInstance(PromiseFlatCString(
+
+  nsCOMPtr<nsIDocumentEncoder> docEncoder = doc->GetCachedEncoder();
+  if (!docEncoder) {
+    docEncoder =
+      do_CreateInstance(PromiseFlatCString(
         nsDependentCString(NS_DOC_ENCODER_CONTRACTID_BASE) +
         NS_ConvertUTF16toUTF8(contentType)
       ).get());
+  }
   if (!(docEncoder || doc->IsHTML())) {
     // This could be some type for which we create a synthetic document.  Try
     // again as XML
     contentType.AssignLiteral("application/xml");
     docEncoder = do_CreateInstance(NS_DOC_ENCODER_CONTRACTID_BASE "application/xml");
   }
 
   NS_ENSURE_TRUE(docEncoder, NS_ERROR_FAILURE);
 
-  nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(doc);
-  rv = docEncoder->Init(domDoc, contentType,
-                        nsIDocumentEncoder::OutputEncodeBasicEntities |
-                        // Output DOM-standard newlines
-                        nsIDocumentEncoder::OutputLFLineBreak |
-                        // Don't do linebreaking that's not present in the source
-                        nsIDocumentEncoder::OutputRaw);
+  rv = docEncoder->NativeInit(doc, contentType,
+                              nsIDocumentEncoder::OutputEncodeBasicEntities |
+                              // Output DOM-standard newlines
+                              nsIDocumentEncoder::OutputLFLineBreak |
+                              // Don't do linebreaking that's not present in
+                              // the source
+                              nsIDocumentEncoder::OutputRaw);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  docEncoder->SetContainerNode(thisNode);
-  return docEncoder->EncodeToString(aInnerHTML);
+  docEncoder->SetNativeContainerNode(this);
+  rv = docEncoder->EncodeToString(aInnerHTML);
+  doc->SetCachedEncoder(docEncoder);
+  return rv;
 }
 
 nsresult
 nsGenericHTMLElement::SetInnerHTML(const nsAString& aInnerHTML)
 {
   nsIDocument* doc = GetOwnerDoc();
   NS_ENSURE_STATE(doc);
 
@@ -779,17 +781,17 @@ nsGenericHTMLElement::ScrollIntoView(PRB
 {
   nsIDocument *document = GetCurrentDoc();
 
   if (!document) {
     return NS_OK;
   }
 
   // Get the presentation shell
-  nsCOMPtr<nsIPresShell> presShell = document->GetPrimaryShell();
+  nsCOMPtr<nsIPresShell> presShell = document->GetShell();
   if (!presShell) {
     return NS_OK;
   }
 
   if (!optional_argc) {
     aTop = PR_TRUE;
   }
 
@@ -1439,17 +1441,17 @@ nsGenericHTMLElement::RestoreFormControl
 // XXX This creates a dependency between content and frames
 nsPresContext*
 nsGenericHTMLElement::GetPresContext()
 {
   // Get the document
   nsIDocument* doc = GetDocument();
   if (doc) {
     // Get presentation shell 0
-    nsIPresShell *presShell = doc->GetPrimaryShell();
+    nsIPresShell *presShell = doc->GetShell();
     if (presShell) {
       return presShell->GetPresContext();
     }
   }
 
   return nsnull;
 }
 
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -1311,17 +1311,26 @@ NS_NewHTML##_elementName##Element(nsINod
 #define NS_DECLARE_NS_NEW_HTML_ELEMENT_AS_SHARED(_elementName)    \
 inline nsGenericHTMLElement*                                      \
 NS_NewHTML##_elementName##Element(nsINodeInfo *aNodeInfo,         \
                                   PRUint32 aFromParser = 0)       \
 {                                                                 \
   return NS_NewHTMLSharedElement(aNodeInfo, aFromParser);         \
 }
 
+// Disable MSVC warning that spams when we pass empty string as only macro arg.
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable:4003)
+#endif
 NS_DECLARE_NS_NEW_HTML_ELEMENT() // HTMLElement
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Shared)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(SharedList)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(SharedObject)
 
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Anchor)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Area)
 #if defined(MOZ_MEDIA)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Audio)
--- a/content/html/content/src/nsHTMLAnchorElement.cpp
+++ b/content/html/content/src/nsHTMLAnchorElement.cpp
@@ -250,17 +250,17 @@ nsHTMLAnchorElement::IsHTMLFocusable(PRB
 {
   if (nsGenericHTMLElement::IsHTMLFocusable(aWithMouse, aIsFocusable, aTabIndex)) {
     return PR_TRUE;
   }
 
   // cannot focus links if there is no link handler
   nsIDocument* doc = GetCurrentDoc();
   if (doc) {
-    nsIPresShell* presShell = doc->GetPrimaryShell();
+    nsIPresShell* presShell = doc->GetShell();
     if (presShell) {
       nsPresContext* presContext = presShell->GetPresContext();
       if (presContext && !presContext->GetLinkHandler()) {
         *aIsFocusable = PR_FALSE;
         return PR_FALSE;
       }
     }
   }
--- a/content/html/content/src/nsHTMLButtonElement.cpp
+++ b/content/html/content/src/nsHTMLButtonElement.cpp
@@ -236,17 +236,17 @@ nsHTMLButtonElement::Click()
     return NS_OK;
 
   mHandlingClick = PR_TRUE;
   // Hold on to the document in case one of the events makes it die or
   // something...
   nsCOMPtr<nsIDocument> doc = GetCurrentDoc();
 
   if (doc) {
-    nsIPresShell *shell = doc->GetPrimaryShell();
+    nsIPresShell *shell = doc->GetShell();
     if (shell) {
       nsRefPtr<nsPresContext> context = shell->GetPresContext();
       if (context) {
         // Click() is never called from native code, but it may be
         // called from chrome JS. Mark this event trusted if Click()
         // is called from chrome code.
         nsMouseEvent event(nsContentUtils::IsCallerChrome(),
                            NS_MOUSE_CLICK, nsnull,
--- a/content/html/content/src/nsHTMLElement.cpp
+++ b/content/html/content/src/nsHTMLElement.cpp
@@ -56,17 +56,25 @@ public:
   NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLElement::)
 
   // nsIDOMHTMLElement
   NS_FORWARD_NSIDOMHTMLELEMENT(nsGenericHTMLElement::)
 
   nsresult Clone(nsINodeInfo* aNodeInfo, nsINode** aResult) const;
 };
 
+// Disable MSVC warning that spams when we pass empty string as only macro arg.
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable:4003)
+#endif
 NS_IMPL_NS_NEW_HTML_ELEMENT() // HTMLElement
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
 
 nsHTMLElement::nsHTMLElement(nsINodeInfo* aNodeInfo)
   : nsGenericHTMLElement(aNodeInfo)
 {
 }
 
 nsHTMLElement::~nsHTMLElement()
 {
--- a/content/html/content/src/nsHTMLInputElement.cpp
+++ b/content/html/content/src/nsHTMLInputElement.cpp
@@ -1705,25 +1705,25 @@ nsHTMLInputElement::Click()
       mType == NS_FORM_INPUT_IMAGE) {
 
     // Strong in case the event kills it
     nsCOMPtr<nsIDocument> doc = GetCurrentDoc();
     if (!doc) {
       return rv;
     }
 
-    nsCOMPtr<nsIPresShell> shell = doc->GetPrimaryShell();
+    nsCOMPtr<nsIPresShell> shell = doc->GetShell();
     nsRefPtr<nsPresContext> context = nsnull;
     if (shell) {
       context = shell->GetPresContext();
     }
 
     if (!context) {
       doc->FlushPendingNotifications(Flush_Frames);
-      shell = doc->GetPrimaryShell();
+      shell = doc->GetShell();
       if (shell) {
         context = shell->GetPresContext();
       }
     }
 
     if (context) {
       // Click() is never called from native code, but it may be
       // called from chrome JS. Mark this event trusted if Click()
--- a/content/html/content/src/nsHTMLTextAreaElement.cpp
+++ b/content/html/content/src/nsHTMLTextAreaElement.cpp
@@ -955,17 +955,17 @@ nsHTMLTextAreaElement::CharacterDataChan
 }
 
 void
 nsHTMLTextAreaElement::ContentAppended(nsIDocument* aDocu