Merge mozilla-central and mozilla-inbound
authorEd Morley <bmo@edmorley.co.uk>
Sun, 04 Dec 2011 15:04:54 +0000
changeset 83030 1bd7482ad4d195aaa4511f241b3de74eac9e8f2c
parent 83029 3d2eac7dcf6693d3763edc0599feab7027dbf72c (current diff)
parent 83010 78de2c2bdad5d3c3d87da866f89733a944afd322 (diff)
child 83031 cb70391c86d9e69a76971518496dbc22214c7c5d
child 83032 e45974ac54991da094759e4386a44e1038ea0720
child 83106 b0ca4b222cb5341847e659a69300620df077ed5d
child 84613 bc612072dddaf5b528bd7259ff922491ef643537
push id519
push userakeybl@mozilla.com
push dateWed, 01 Feb 2012 00:38:35 +0000
treeherdermozilla-beta@788ea1ef610b [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone11.0a1
first release with
nightly linux32
1bd7482ad4d1 / 11.0a1 / 20111205031110 / files
nightly linux64
1bd7482ad4d1 / 11.0a1 / 20111205031110 / files
nightly mac
1bd7482ad4d1 / 11.0a1 / 20111205031110 / files
nightly win32
1bd7482ad4d1 / 11.0a1 / 20111205031110 / files
nightly win64
1bd7482ad4d1 / 11.0a1 / 20111205031110 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge mozilla-central and mozilla-inbound
content/html/content/src/nsHTMLMediaElement.cpp
js/xpconnect/idl/xpccomponents.idl
js/xpconnect/src/XPCComponents.cpp
--- a/accessible/src/atk/nsMaiInterfaceDocument.cpp
+++ b/accessible/src/atk/nsMaiInterfaceDocument.cpp
@@ -76,34 +76,16 @@ getDocumentLocaleCB(AtkDocument *aDocume
     nsAutoString locale;
     docAccessNode->GetLanguage(locale);
     if (locale.IsEmpty()) {
       return nsnull;
     }
     return nsAccessibleWrap::ReturnString(locale);
 }
 
-const gchar *
-getDocumentTypeCB(AtkDocument *aDocument)
-{
-    nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument));
-    if (!accWrap)
-        return nsnull;
-
-    nsCOMPtr<nsIAccessibleDocument> accDocument;
-    accWrap->QueryInterface(NS_GET_IID(nsIAccessibleDocument),
-                            getter_AddRefs(accDocument));
-    NS_ENSURE_TRUE(accDocument, nsnull);
-
-    nsAutoString mimeType;
-    nsresult rv = accDocument->GetMimeType(mimeType);
-    NS_ENSURE_SUCCESS(rv, nsnull);
-    return nsAccessibleWrap::ReturnString(mimeType);
-}
-
 static inline GSList *
 prependToList(GSList *aList, const char *const aName, const nsAutoString &aValue)
 {
     // libspi will free these
     AtkAttribute *atkAttr = (AtkAttribute *)g_malloc(sizeof(AtkAttribute));
     atkAttr->name = g_strdup(aName);
     atkAttr->value = g_strdup(NS_ConvertUTF16toUTF8(aValue).get());
     return g_slist_prepend(aList, atkAttr);
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -655,32 +655,16 @@ nsCoreUtils::GetFirstSensibleColumn(nsIT
   nsCOMPtr<nsITreeColumn> column;
   cols->GetFirstColumn(getter_AddRefs(column));
   if (column && IsColumnHidden(column))
     return GetNextSensibleColumn(column);
 
   return column.forget();
 }
 
-already_AddRefed<nsITreeColumn>
-nsCoreUtils::GetLastSensibleColumn(nsITreeBoxObject *aTree)
-{
-  nsCOMPtr<nsITreeColumns> cols;
-  aTree->GetColumns(getter_AddRefs(cols));
-  if (!cols)
-    return nsnull;
-
-  nsCOMPtr<nsITreeColumn> column;
-  cols->GetLastColumn(getter_AddRefs(column));
-  if (column && IsColumnHidden(column))
-    return GetPreviousSensibleColumn(column);
-
-  return column.forget();
-}
-
 PRUint32
 nsCoreUtils::GetSensibleColumnCount(nsITreeBoxObject *aTree)
 {
   PRUint32 count = 0;
 
   nsCOMPtr<nsITreeColumns> cols;
   aTree->GetColumns(getter_AddRefs(cols));
   if (!cols)
--- a/accessible/src/base/nsCoreUtils.h
+++ b/accessible/src/base/nsCoreUtils.h
@@ -323,22 +323,16 @@ public:
 
   /**
    * Return first sensible column for the given tree box object.
    */
   static already_AddRefed<nsITreeColumn>
     GetFirstSensibleColumn(nsITreeBoxObject *aTree);
 
   /**
-   * Return last sensible column for the given tree box object.
-   */
-  static already_AddRefed<nsITreeColumn>
-    GetLastSensibleColumn(nsITreeBoxObject *aTree);
-
-  /**
    * Return sensible columns count for the given tree box object.
    */
   static PRUint32 GetSensibleColumnCount(nsITreeBoxObject *aTree);
 
   /**
    * Return sensible column at the given index for the given tree box object.
    */
   static already_AddRefed<nsITreeColumn>
--- a/content/base/src/nsAttrAndChildArray.cpp
+++ b/content/base/src/nsAttrAndChildArray.cpp
@@ -362,41 +362,16 @@ nsAttrAndChildArray::AttrAt(PRUint32 aPo
   if (aPos < mapped) {
     return mImpl->mMappedAttrs->AttrAt(aPos);
   }
 
   return &ATTRS(mImpl)[aPos - mapped].mValue;
 }
 
 nsresult
-nsAttrAndChildArray::SetAttr(nsIAtom* aLocalName, const nsAString& aValue)
-{
-  PRUint32 i, slotCount = AttrSlotCount();
-  for (i = 0; i < slotCount && AttrSlotIsTaken(i); ++i) {
-    if (ATTRS(mImpl)[i].mName.Equals(aLocalName)) {
-      ATTRS(mImpl)[i].mValue.SetTo(aValue);
-
-      return NS_OK;
-    }
-  }
-
-  NS_ENSURE_TRUE(slotCount < ATTRCHILD_ARRAY_MAX_ATTR_COUNT,
-                 NS_ERROR_FAILURE);
-
-  if (i == slotCount && !AddAttrSlot()) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  new (&ATTRS(mImpl)[i].mName) nsAttrName(aLocalName);
-  new (&ATTRS(mImpl)[i].mValue) nsAttrValue(aValue);
-
-  return NS_OK;
-}
-
-nsresult
 nsAttrAndChildArray::SetAndTakeAttr(nsIAtom* aLocalName, nsAttrValue& aValue)
 {
   PRUint32 i, slotCount = AttrSlotCount();
   for (i = 0; i < slotCount && AttrSlotIsTaken(i); ++i) {
     if (ATTRS(mImpl)[i].mName.Equals(aLocalName)) {
       ATTRS(mImpl)[i].mValue.Reset();
       ATTRS(mImpl)[i].mValue.SwapValueWith(aValue);
 
--- a/content/base/src/nsAttrAndChildArray.h
+++ b/content/base/src/nsAttrAndChildArray.h
@@ -98,17 +98,16 @@ public:
   // Like RemoveChildAt but hands the reference to the child being
   // removed back to the caller instead of just releasing it.
   already_AddRefed<nsIContent> TakeChildAt(PRUint32 aPos);
   PRInt32 IndexOfChild(nsINode* aPossibleChild) const;
 
   PRUint32 AttrCount() const;
   const nsAttrValue* GetAttr(nsIAtom* aLocalName, PRInt32 aNamespaceID = kNameSpaceID_None) const;
   const nsAttrValue* AttrAt(PRUint32 aPos) const;
-  nsresult SetAttr(nsIAtom* aLocalName, const nsAString& aValue);
   nsresult SetAndTakeAttr(nsIAtom* aLocalName, nsAttrValue& aValue);
   nsresult SetAndTakeAttr(nsINodeInfo* aName, nsAttrValue& aValue);
 
   // Remove the attr at position aPos.  The value of the attr is placed in
   // aValue; any value that was already in aValue is destroyed.
   nsresult RemoveAttrAt(PRUint32 aPos, nsAttrValue& aValue);
 
   // Returns attribute name at given position, *not* out-of-bounds safe
--- a/content/base/src/nsStyleLinkElement.cpp
+++ b/content/base/src/nsStyleLinkElement.cpp
@@ -174,21 +174,21 @@ PRUint32 nsStyleLinkElement::ParseLinkTy
   PRUint32 linkMask = 0;
   nsAString::const_iterator start, done;
   aTypes.BeginReading(start);
   aTypes.EndReading(done);
   if (start == done)
     return linkMask;
 
   nsAString::const_iterator current(start);
-  bool inString = !nsCRT::IsAsciiSpace(*current);
+  bool inString = !nsContentUtils::IsHTMLWhitespace(*current);
   nsAutoString subString;
   
   while (current != done) {
-    if (nsCRT::IsAsciiSpace(*current)) {
+    if (nsContentUtils::IsHTMLWhitespace(*current)) {
       if (inString) {
         ToLowerCase(Substring(start, current), subString);
         linkMask |= ToLinkMask(subString);
         inString = false;
       }
     }
     else {
       if (!inString) {
--- a/content/base/src/nsXMLContentSerializer.cpp
+++ b/content/base/src/nsXMLContentSerializer.cpp
@@ -1147,31 +1147,16 @@ nsXMLContentSerializer::CheckElementEnd(
                                         bool & aForceFormat,
                                         nsAString& aStr)
 {
   // We don't output a separate end tag for empty element
   aForceFormat = false;
   return aContent->GetChildCount() > 0;
 }
 
-void
-nsXMLContentSerializer::AppendToString(const PRUnichar* aStr,
-                                       PRInt32 aLength,
-                                       nsAString& aOutputStr)
-{
-  if (mBodyOnly && !mInBody) {
-    return;
-  }
-  PRInt32 length = (aLength == -1) ? nsCRT::strlen(aStr) : aLength;
-
-  mColPos += length;
-
-  aOutputStr.Append(aStr, length);
-}
-
 void 
 nsXMLContentSerializer::AppendToString(const PRUnichar aChar,
                                        nsAString& aOutputStr)
 {
   if (mBodyOnly && !mInBody) {
     return;
   }
   mColPos += 1;
--- a/content/base/src/nsXMLContentSerializer.h
+++ b/content/base/src/nsXMLContentSerializer.h
@@ -98,23 +98,16 @@ class nsXMLContentSerializer : public ns
   NS_IMETHOD Flush(nsAString& aStr) { return NS_OK; }
 
   NS_IMETHOD AppendDocumentStart(nsIDocument *aDocument,
                                  nsAString& aStr);
 
  protected:
 
   /**
-   * Appends a PRUnichar string and increments the column position
-   */
-  void AppendToString(const PRUnichar* aStr,
-                      PRInt32 aLength,
-                      nsAString& aOutputStr);
-
-  /**
    * Appends a PRUnichar character and increments the column position
    */
   void AppendToString(const PRUnichar aChar,
                       nsAString& aOutputStr);
 
   /**
    * Appends a nsAString string and increments the column position
    */
--- a/content/canvas/src/CanvasUtils.cpp
+++ b/content/canvas/src/CanvasUtils.cpp
@@ -96,44 +96,16 @@ DoDrawImageSecurityCheck(nsHTMLCanvasEle
     if (NS_SUCCEEDED(rv) && subsumes) {
         // This canvas has access to that image anyway
         return;
     }
 
     aCanvasElement->SetWriteOnly();
 }
 
-void
-LogMessage (const nsCString& errorString)
-{
-    nsCOMPtr<nsIConsoleService> console(do_GetService(NS_CONSOLESERVICE_CONTRACTID));
-    if (!console)
-        return;
-
-    console->LogStringMessage(NS_ConvertUTF8toUTF16(errorString).get());
-    fprintf(stderr, "%s\n", errorString.get());
-}
-
-void
-LogMessagef (const char *fmt, ...)
-{
-    va_list ap;
-    va_start(ap, fmt);
-    char buf[256];
-
-    nsCOMPtr<nsIConsoleService> console(do_GetService(NS_CONSOLESERVICE_CONTRACTID));
-    if (console) {
-        PR_vsnprintf(buf, 256, fmt, ap);
-        console->LogStringMessage(NS_ConvertUTF8toUTF16(nsDependentCString(buf)).get());
-        fprintf(stderr, "%s\n", buf);
-    }
-
-    va_end(ap);
-}
-
 bool
 CoerceDouble(jsval v, double* d)
 {
     if (JSVAL_IS_DOUBLE(v)) {
         *d = JSVAL_TO_DOUBLE(v);
     } else if (JSVAL_IS_INT(v)) {
         *d = double(JSVAL_TO_INT(v));
     } else if (JSVAL_IS_VOID(v)) {
--- a/content/canvas/src/CanvasUtils.h
+++ b/content/canvas/src/CanvasUtils.h
@@ -72,19 +72,16 @@ inline bool CheckSaneSubrectSize(PRInt32
 // Flag aCanvasElement as write-only if drawing an image with aPrincipal
 // onto it would make it such.
 
 void DoDrawImageSecurityCheck(nsHTMLCanvasElement *aCanvasElement,
                               nsIPrincipal *aPrincipal,
                               bool forceWriteOnly,
                               bool CORSUsed);
 
-void LogMessage (const nsCString& errorString);
-void LogMessagef (const char *fmt, ...);
-
 // Make a double out of |v|, treating undefined values as 0.0 (for
 // the sake of sparse arrays).  Return true iff coercion
 // succeeded.
 bool CoerceDouble(jsval v, double* d);
 
 // Return true iff the conversion succeeded, false otherwise.  *rv is
 // the value to return to script if this returns false.
 bool JSValToMatrix(JSContext* cx, const jsval& val,
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -3988,29 +3988,32 @@ WebGLContext::ConvertImage(size_t width,
             return;
     }
 }
 
 nsresult
 WebGLContext::DOMElementToImageSurface(nsIDOMElement *imageOrCanvas,
                                        gfxImageSurface **imageOut, int *format)
 {
-    gfxImageSurface *surf = nsnull;
+    nsCOMPtr<nsIContent> content = do_QueryInterface(imageOrCanvas);
+    if (!content) {
+        return NS_ERROR_FAILURE;
+    }        
 
     PRUint32 flags =
         nsLayoutUtils::SFE_WANT_NEW_SURFACE |
         nsLayoutUtils::SFE_WANT_IMAGE_SURFACE;
 
     if (mPixelStoreColorspaceConversion == LOCAL_GL_NONE)
         flags |= nsLayoutUtils::SFE_NO_COLORSPACE_CONVERSION;
     if (!mPixelStorePremultiplyAlpha)
         flags |= nsLayoutUtils::SFE_NO_PREMULTIPLY_ALPHA;
 
     nsLayoutUtils::SurfaceFromElementResult res =
-        nsLayoutUtils::SurfaceFromElement(imageOrCanvas, flags);
+        nsLayoutUtils::SurfaceFromElement(content->AsElement(), flags);
     if (!res.mSurface)
         return NS_ERROR_FAILURE;
     if (res.mSurface->GetType() != gfxASurface::SurfaceTypeImage) {
         // SurfaceFromElement lied!
         return NS_ERROR_FAILURE;
     }
 
     // We disallow loading cross-domain images that have not been validated
@@ -4029,35 +4032,34 @@ WebGLContext::DOMElementToImageSurface(n
         nsresult rv = HTMLCanvasElement()->NodePrincipal()->Subsumes(res.mPrincipal, &subsumes);
         if (NS_FAILED(rv) || !subsumes) {
             LogMessageIfVerbose("It is forbidden to load a WebGL texture from a cross-domain element that has not been validated with CORS. "
                                 "See https://developer.mozilla.org/en/WebGL/Cross-Domain_Textures");
             return NS_ERROR_DOM_SECURITY_ERR;
         }
     }
 
-    // part 2: if the DOM element is a canvas, check that it's not write-only. That would indicate a tainted canvas,
-    // i.e. a canvas that could contain cross-domain image data.
-    nsCOMPtr<nsIContent> maybeDOMCanvas = do_QueryInterface(imageOrCanvas);
-    if (maybeDOMCanvas && maybeDOMCanvas->IsHTML(nsGkAtoms::canvas)) {
-        nsHTMLCanvasElement *canvas = static_cast<nsHTMLCanvasElement*>(maybeDOMCanvas.get());
+    // part 2: if the DOM element is a canvas, check that it's not write-only.
+    // That would indicate a tainted canvas, i.e. a canvas that could contain
+    // cross-domain image data.
+    if (nsHTMLCanvasElement* canvas = nsHTMLCanvasElement::FromContent(content)) {
         if (canvas->IsWriteOnly()) {
             LogMessageIfVerbose("The canvas used as source for texImage2D here is tainted (write-only). It is forbidden "
                                 "to load a WebGL texture from a tainted canvas. A Canvas becomes tainted for example "
                                 "when a cross-domain image is drawn on it. "
                                 "See https://developer.mozilla.org/en/WebGL/Cross-Domain_Textures");
             return NS_ERROR_DOM_SECURITY_ERR;
         }
     }
 
     // End of security checks, now we should be safe regarding cross-domain images
     // Notice that there is never a need to mark the WebGL canvas as write-only, since we reject write-only/cross-domain
     // texture sources in the first place.
 
-    surf = static_cast<gfxImageSurface*>(res.mSurface.get());
+    gfxImageSurface* surf = static_cast<gfxImageSurface*>(res.mSurface.get());
 
     res.mSurface.forget();
     *imageOut = surf;
 
     switch (surf->Format()) {
         case gfxASurface::ImageFormatARGB32:
             *format = WebGLTexelFormat::BGRA8; // careful, our ARGB means BGRA
             break;
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -1808,50 +1808,50 @@ nsCanvasRenderingContext2D::CreateRadial
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::CreatePattern(nsIDOMHTMLElement *image,
                                           const nsAString& repeat,
                                           nsIDOMCanvasPattern **_retval)
 {
-    if (!image) {
+    nsCOMPtr<nsIContent> content = do_QueryInterface(image);
+    if (!content) {
         return NS_ERROR_DOM_TYPE_MISMATCH_ERR;
     }
+
     gfxPattern::GraphicsExtend extend;
-
     if (repeat.IsEmpty() || repeat.EqualsLiteral("repeat")) {
         extend = gfxPattern::EXTEND_REPEAT;
     } else if (repeat.EqualsLiteral("repeat-x")) {
         // XX
         extend = gfxPattern::EXTEND_REPEAT;
     } else if (repeat.EqualsLiteral("repeat-y")) {
         // XX
         extend = gfxPattern::EXTEND_REPEAT;
     } else if (repeat.EqualsLiteral("no-repeat")) {
         extend = gfxPattern::EXTEND_NONE;
     } else {
         // XXX ERRMSG we need to report an error to developers here! (bug 329026)
         return NS_ERROR_DOM_SYNTAX_ERR;
     }
 
-    nsCOMPtr<nsIContent> content = do_QueryInterface(image);
     nsHTMLCanvasElement* canvas = nsHTMLCanvasElement::FromContent(content);
     if (canvas) {
         nsIntSize size = canvas->GetSize();
         if (size.width == 0 || size.height == 0) {
             return NS_ERROR_DOM_INVALID_STATE_ERR;
         }
     }
 
     // The canvas spec says that createPattern should use the first frame
     // of animated images
     nsLayoutUtils::SurfaceFromElementResult res =
-        nsLayoutUtils::SurfaceFromElement(image, nsLayoutUtils::SFE_WANT_FIRST_FRAME |
-                                                 nsLayoutUtils::SFE_WANT_NEW_SURFACE);
+        nsLayoutUtils::SurfaceFromElement(content->AsElement(),
+            nsLayoutUtils::SFE_WANT_FIRST_FRAME | nsLayoutUtils::SFE_WANT_NEW_SURFACE);
     if (!res.mSurface)
         return NS_ERROR_NOT_AVAILABLE;
 
     nsRefPtr<gfxPattern> thebespat = new gfxPattern(res.mSurface);
 
     thebespat->SetExtend(extend);
 
     nsRefPtr<nsCanvasPattern> pat = new nsCanvasPattern(thebespat, res.mPrincipal,
@@ -3394,21 +3394,21 @@ NS_IMETHODIMP
 nsCanvasRenderingContext2D::DrawImage(nsIDOMElement *imgElt, float a1,
                                       float a2, float a3, float a4, float a5,
                                       float a6, float a7, float a8,
                                       PRUint8 optional_argc)
 {
     if (!EnsureSurface())
         return NS_ERROR_FAILURE;
 
-    if (!imgElt) {
+    nsCOMPtr<nsIContent> content = do_QueryInterface(imgElt);
+    if (!content) {
         return NS_ERROR_DOM_TYPE_MISMATCH_ERR;
     }
 
-    nsCOMPtr<nsIContent> content = do_QueryInterface(imgElt);
     nsHTMLCanvasElement* canvas = nsHTMLCanvasElement::FromContent(content);
     if (canvas) {
         nsIntSize size = canvas->GetSize();
         if (size.width == 0 || size.height == 0) {
             return NS_ERROR_DOM_INVALID_STATE_ERR;
         }
     }
 
@@ -3418,27 +3418,28 @@ nsCanvasRenderingContext2D::DrawImage(ns
     nsRefPtr<gfxASurface> imgsurf =
       CanvasImageCache::Lookup(imgElt, HTMLCanvasElement(), &imgSize);
 
     if (!imgsurf) {
         // The canvas spec says that drawImage should draw the first frame
         // of animated images
         PRUint32 sfeFlags = nsLayoutUtils::SFE_WANT_FIRST_FRAME;
         nsLayoutUtils::SurfaceFromElementResult res =
-            nsLayoutUtils::SurfaceFromElement(imgElt, sfeFlags);
+            nsLayoutUtils::SurfaceFromElement(content->AsElement(), sfeFlags);
         if (!res.mSurface) {
             // Spec says to silently do nothing if the element is still loading.
             return res.mIsStillLoading ? NS_OK : NS_ERROR_NOT_AVAILABLE;
         }
 
         // Force a copy if we're using drawImage with our destination
         // as a source to work around some Cairo self-copy semantics issues.
         if (res.mSurface == mSurface) {
             sfeFlags |= nsLayoutUtils::SFE_WANT_NEW_SURFACE;
-            res = nsLayoutUtils::SurfaceFromElement(imgElt, sfeFlags);
+            res = nsLayoutUtils::SurfaceFromElement(content->AsElement(),
+                                                    sfeFlags);
             if (!res.mSurface)
                 return NS_ERROR_NOT_AVAILABLE;
         }
 
         imgsurf = res.mSurface.forget();
         imgSize = res.mSize;
 
         if (mCanvasElement) {
--- a/content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
@@ -1884,17 +1884,18 @@ nsCanvasRenderingContext2DAzure::CreateR
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::CreatePattern(nsIDOMHTMLElement *image,
                                                const nsAString& repeat,
                                                nsIDOMCanvasPattern **_retval)
 {
-  if (!image) {
+  nsCOMPtr<nsIContent> content = do_QueryInterface(image);
+  if (!content) {
     return NS_ERROR_DOM_TYPE_MISMATCH_ERR;
   }
 
   nsCanvasPatternAzure::RepeatMode repeatMode =
     nsCanvasPatternAzure::NOREPEAT;
 
   if (repeat.IsEmpty() || repeat.EqualsLiteral("repeat")) {
     repeatMode = nsCanvasPatternAzure::REPEAT;
@@ -1903,19 +1904,17 @@ nsCanvasRenderingContext2DAzure::CreateP
   } else if (repeat.EqualsLiteral("repeat-y")) {
     repeatMode = nsCanvasPatternAzure::REPEATY;
   } else if (repeat.EqualsLiteral("no-repeat")) {
     repeatMode = nsCanvasPatternAzure::NOREPEAT;
   } else {
     return NS_ERROR_DOM_SYNTAX_ERR;
   }
 
-  nsCOMPtr<nsIContent> content = do_QueryInterface(image);
   nsHTMLCanvasElement* canvas = nsHTMLCanvasElement::FromContent(content);
-
   if (canvas) {
     nsIntSize size = canvas->GetSize();
     if (size.width == 0 || size.height == 0) {
       return NS_ERROR_DOM_INVALID_STATE_ERR;
     }
   }
 
   // Special case for Canvas, which could be an Azure canvas!
@@ -1934,18 +1933,18 @@ nsCanvasRenderingContext2DAzure::CreateP
         return NS_OK;
       }
     }
   }
 
   // The canvas spec says that createPattern should use the first frame
   // of animated images
   nsLayoutUtils::SurfaceFromElementResult res =
-    nsLayoutUtils::SurfaceFromElement(image, nsLayoutUtils::SFE_WANT_FIRST_FRAME |
-                                              nsLayoutUtils::SFE_WANT_NEW_SURFACE);
+    nsLayoutUtils::SurfaceFromElement(content->AsElement(),
+      nsLayoutUtils::SFE_WANT_FIRST_FRAME | nsLayoutUtils::SFE_WANT_NEW_SURFACE);
 
   if (!res.mSurface) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   // Ignore nsnull cairo surfaces! See bug 666312.
   if (!res.mSurface->CairoSurface()) {
     return NS_OK;
@@ -3565,17 +3564,18 @@ nsCanvasRenderingContext2DAzure::IsPoint
 //   -- render the region defined by (sx,sy,sw,wh) in image-local space into the region (dx,dy,dw,dh) on the canvas
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::DrawImage(nsIDOMElement *imgElt, float a1,
                                            float a2, float a3, float a4, float a5,
                                            float a6, float a7, float a8,
                                            PRUint8 optional_argc)
 {
-  if (!imgElt) {
+  nsCOMPtr<nsIContent> content = do_QueryInterface(imgElt);
+  if (!content) {
     return NS_ERROR_DOM_TYPE_MISMATCH_ERR;
   }
 
   if (optional_argc == 0) {
     if (!FloatValidate(a1, a2)) {
       return NS_OK;
     }
   } else if (optional_argc == 2) {
@@ -3586,17 +3586,16 @@ nsCanvasRenderingContext2DAzure::DrawIma
     if (!FloatValidate(a1, a2, a3, a4, a5, a6) || !FloatValidate(a7, a8)) {
       return NS_OK;
     }
   }
 
   double sx,sy,sw,sh;
   double dx,dy,dw,dh;
 
-  nsCOMPtr<nsIContent> content = do_QueryInterface(imgElt);
   nsHTMLCanvasElement* canvas = nsHTMLCanvasElement::FromContent(content);
   if (canvas) {
     nsIntSize size = canvas->GetSize();
     if (size.width == 0 || size.height == 0) {
       return NS_ERROR_DOM_INVALID_STATE_ERR;
     }
   }
     
@@ -3638,17 +3637,17 @@ nsCanvasRenderingContext2DAzure::DrawIma
     }
   }
 
   if (!srcSurf) {
     // The canvas spec says that drawImage should draw the first frame
     // of animated images
     PRUint32 sfeFlags = nsLayoutUtils::SFE_WANT_FIRST_FRAME;
     nsLayoutUtils::SurfaceFromElementResult res =
-      nsLayoutUtils::SurfaceFromElement(imgElt, sfeFlags);
+      nsLayoutUtils::SurfaceFromElement(content->AsElement(), sfeFlags);
 
     if (!res.mSurface) {
       // Spec says to silently do nothing if the element is still loading.
       return res.mIsStillLoading ? NS_OK : NS_ERROR_NOT_AVAILABLE;
     }
 
     // Ignore cairo surfaces that are bad! See bug 666312.
     if (res.mSurface->CairoStatus()) {
--- a/content/html/content/public/nsHTMLVideoElement.h
+++ b/content/html/content/public/nsHTMLVideoElement.h
@@ -43,16 +43,24 @@
 
 class nsHTMLVideoElement : public nsHTMLMediaElement,
                            public nsIDOMHTMLVideoElement
 {
 public:
   nsHTMLVideoElement(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsHTMLVideoElement();
 
+  static nsHTMLVideoElement* FromContent(nsIContent* aPossibleVideo)
+  {
+    if (!aPossibleVideo || !aPossibleVideo->IsHTML(nsGkAtoms::video)) {
+      return NULL;
+    }
+    return static_cast<nsHTMLVideoElement*>(aPossibleVideo);
+  }
+
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsHTMLMediaElement::)
 
   // nsIDOMElement
   NS_FORWARD_NSIDOMELEMENT(nsHTMLMediaElement::)
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -2685,28 +2685,27 @@ nsHTMLMediaElement::CopyInnerTo(nsGeneri
   NS_ENSURE_SUCCESS(rv, rv);
   if (aDest->OwnerDoc()->IsStaticDocument()) {
     nsHTMLMediaElement* dest = static_cast<nsHTMLMediaElement*>(aDest);
     if (mPrintSurface) {
       dest->mPrintSurface = mPrintSurface;
       dest->mMediaSize = mMediaSize;
     } else {
       nsIFrame* frame = GetPrimaryFrame();
-      nsCOMPtr<nsIDOMElement> elem;
+      Element* element;
       if (frame && frame->GetType() == nsGkAtoms::HTMLVideoFrame &&
           static_cast<nsVideoFrame*>(frame)->ShouldDisplayPoster()) {
-        elem = do_QueryInterface(static_cast<nsVideoFrame*>(frame)->
-                                 GetPosterImage());
+        nsIContent* content = static_cast<nsVideoFrame*>(frame)->GetPosterImage();
+        element = content ? content->AsElement() : NULL;
       } else {
-        elem = do_QueryInterface(
-          static_cast<nsGenericElement*>(const_cast<nsHTMLMediaElement*>(this)));
+        element = const_cast<nsHTMLMediaElement*>(this);
       }
 
       nsLayoutUtils::SurfaceFromElementResult res =
-        nsLayoutUtils::SurfaceFromElement(elem,
+        nsLayoutUtils::SurfaceFromElement(element,
                                           nsLayoutUtils::SFE_WANT_NEW_SURFACE);
       dest->mPrintSurface = res.mSurface;
       dest->mMediaSize = nsIntSize(res.mSize.width, res.mSize.height);
     }
   }
   return rv;
 }
 
--- a/content/xul/document/src/nsXULDocument.cpp
+++ b/content/xul/document/src/nsXULDocument.cpp
@@ -2359,33 +2359,16 @@ nsXULDocument::ContextStack::SetTopIndex
     if (mDepth == 0)
         return NS_ERROR_UNEXPECTED;
 
     mTop->mIndex = aIndex;
     return NS_OK;
 }
 
 
-bool
-nsXULDocument::ContextStack::IsInsideXULTemplate()
-{
-    if (mDepth) {
-        for (nsIContent* element = mTop->mElement; element;
-             element = element->GetParent()) {
-
-            if (element->NodeInfo()->Equals(nsGkAtoms::_template,
-                                            kNameSpaceID_XUL)) {
-                return true;
-            }
-        }
-    }
-    return false;
-}
-
-
 //----------------------------------------------------------------------
 //
 // Content model walking routines
 //
 
 nsresult
 nsXULDocument::PrepareToWalk()
 {
--- a/content/xul/document/src/nsXULDocument.h
+++ b/content/xul/document/src/nsXULDocument.h
@@ -352,18 +352,16 @@ protected:
 
         PRInt32 Depth() { return mDepth; }
 
         nsresult Push(nsXULPrototypeElement* aPrototype, nsIContent* aElement);
         nsresult Pop();
         nsresult Peek(nsXULPrototypeElement** aPrototype, nsIContent** aElement, PRInt32* aIndex);
 
         nsresult SetTopIndex(PRInt32 aIndex);
-
-        bool IsInsideXULTemplate();
     };
 
     friend class ContextStack;
     ContextStack mContextStack;
 
     enum State { eState_Master, eState_Overlay };
     State mState;
 
--- a/content/xul/templates/src/nsRuleNetwork.cpp
+++ b/content/xul/templates/src/nsRuleNetwork.cpp
@@ -449,23 +449,16 @@ TestNode::Constrain(InstantiationSet& aI
 
     PR_LOG(gXULTemplateLog, PR_LOG_DEBUG,
            ("TestNode[%p]: Constrain() end", this));
 
     return rv;
 }
 
 
-bool
-TestNode::HasAncestor(const ReteNode* aNode) const
-{
-    return aNode == this || (mParent && mParent->HasAncestor(aNode));
-}
-
-
 //----------------------------------------------------------------------
 
 ReteNodeSet::ReteNodeSet()
     : mNodes(nsnull), mCount(0), mCapacity(0)
 {
 }
 
 ReteNodeSet::~ReteNodeSet()
--- a/content/xul/templates/src/nsRuleNetwork.h
+++ b/content/xul/templates/src/nsRuleNetwork.h
@@ -874,24 +874,16 @@ public:
      *        isn't important to the caller.
      * @return NS_OK if no errors occurred.
      */
     virtual nsresult FilterInstantiations(InstantiationSet& aInstantiations,
                                           bool* aCantHandleYet) const = 0;
     //XXX probably better named "ApplyConstraints" or "Discrminiate" or something
 
     /**
-     * Determine if this node has another node as its direct ancestor.
-     * @param aNode the node to look for.
-     * @return true if aNode is a direct ancestor of this node, false
-     *   otherwise.
-     */
-    bool HasAncestor(const ReteNode* aNode) const;
-
-    /**
      * Add another node as a child of this node.
      * @param aNode the node to add.
      * @return NS_OK if no errors occur.
      */
     nsresult AddChild(ReteNode* aNode) { return mKids.Add(aNode); }
 
     /**
      * Remove all the children of this node
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -864,20 +864,28 @@ nsDOMWindowUtils::NodesFromRect(float aX
   nsCOMPtr<nsIDocument> doc(do_QueryInterface(mWindow->GetExtantDocument()));
   NS_ENSURE_STATE(doc);
 
   return doc->NodesFromRectHelper(aX, aY, aTopSize, aRightSize, aBottomSize, aLeftSize, 
                                   aIgnoreRootScrollFrame, aFlushLayout, aReturn);
 }
 
 static already_AddRefed<gfxImageSurface>
-CanvasToImageSurface(nsIDOMHTMLCanvasElement *canvas)
+CanvasToImageSurface(nsIDOMHTMLCanvasElement* aCanvas)
 {
+  nsCOMPtr<nsINode> node = do_QueryInterface(aCanvas);
+  if (!node) {
+    return nsnull;
+  }
+
+  NS_ABORT_IF_FALSE(node->IsElement(),
+                    "An nsINode that implements nsIDOMHTMLCanvasElement should "
+                    "be an element.");
   nsLayoutUtils::SurfaceFromElementResult result =
-    nsLayoutUtils::SurfaceFromElement(canvas,
+    nsLayoutUtils::SurfaceFromElement(node->AsElement(),
                                       nsLayoutUtils::SFE_WANT_IMAGE_SURFACE);
   return static_cast<gfxImageSurface*>(result.mSurface.forget().get());
 }
 
 NS_IMETHODIMP
 nsDOMWindowUtils::CompareCanvases(nsIDOMHTMLCanvasElement *aCanvas1,
                                   nsIDOMHTMLCanvasElement *aCanvas2,
                                   PRUint32* aMaxDifference,
@@ -1437,54 +1445,30 @@ nsDOMWindowUtils::SendContentCommandEven
     event.mTransferable = aTransferable;
   }
 
   nsEventStatus status;
   return widget->DispatchEvent(&event, status);
 }
 
 NS_IMETHODIMP
-nsDOMWindowUtils::GetClassName(char **aName)
+nsDOMWindowUtils::GetClassName(const JS::Value& aObject, JSContext* aCx, char** aName)
 {
   if (!nsContentUtils::IsCallerTrustedForRead()) {
     return NS_ERROR_DOM_SECURITY_ERR;
   }
 
-  // get the xpconnect native call context
-  nsAXPCNativeCallContext *cc = nsnull;
-  nsContentUtils::XPConnect()->GetCurrentNativeCallContext(&cc);
-  if(!cc)
-    return NS_ERROR_FAILURE;
-
-  // Get JSContext of current call
-  JSContext* cx;
-  nsresult rv = cc->GetJSContext(&cx);
-  if(NS_FAILED(rv) || !cx)
-    return NS_ERROR_FAILURE;
+  // Our argument must be a non-null object.
+  if (JSVAL_IS_PRIMITIVE(aObject)) {
+    return NS_ERROR_XPC_BAD_CONVERT_JS;
+  }
 
-  // get argc and argv and verify arg count
-  PRUint32 argc;
-  rv = cc->GetArgc(&argc);
-  if(NS_FAILED(rv))
-    return NS_ERROR_FAILURE;
-
-  if(argc < 1)
-    return NS_ERROR_XPC_NOT_ENOUGH_ARGS;
-
-  jsval* argv;
-  rv = cc->GetArgvPtr(&argv);
-  if(NS_FAILED(rv) || !argv)
-    return NS_ERROR_FAILURE;
-
-  // Our argument must be a non-null object.
-  if(JSVAL_IS_PRIMITIVE(argv[0]))
-    return NS_ERROR_XPC_BAD_CONVERT_JS;
-
-  *aName = NS_strdup(JS_GET_CLASS(cx, JSVAL_TO_OBJECT(argv[0]))->name);
-  return *aName ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+  *aName = NS_strdup(JS_GET_CLASS(aCx, JSVAL_TO_OBJECT(aObject))->name);
+  NS_ABORT_IF_FALSE(*aName, "NS_strdup should be infallible.");
+  return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMWindowUtils::GetVisitedDependentComputedStyle(
                     nsIDOMElement *aElement, const nsAString& aPseudoElement,
                     const nsAString& aPropertyName, nsAString& aResult)
 {
   aResult.Truncate();
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl
+++ b/dom/interfaces/base/nsIDOMWindowUtils.idl
@@ -63,17 +63,17 @@ interface nsIDOMElement;
 interface nsIDOMHTMLCanvasElement;
 interface nsIDOMEvent;
 interface nsITransferable;
 interface nsIQueryContentEventResult;
 interface nsIDOMWindow;
 interface nsIDOMFile;
 interface nsIFile;
 
-[scriptable, uuid(c5cf91b3-0b89-4417-b13c-5540ba6ebde8)]
+[scriptable, uuid(bf868921-0288-4799-a806-2fa642590197)]
 interface nsIDOMWindowUtils : nsISupports {
 
   /**
    * Image animation mode of the window. When this attribute's value
    * is changed, the implementation should set all images in the window
    * to the given value. That is, when set to kDontAnimMode, all images
    * will stop animating. The attribute's value must be one of the
    * animationMode values from imgIContainer.
@@ -552,17 +552,17 @@ interface nsIDOMWindowUtils : nsISupport
   boolean dispatchDOMEventViaPresShell(in nsIDOMNode aTarget,
                                        in nsIDOMEvent aEvent,
                                        in boolean aTrusted);
 
   /**
    * Returns the real classname (possibly of the mostly-transparent security
    * wrapper) of aObj.
    */
-  string getClassName(/*in JSObjectPtr aObj*/);
+  [implicit_jscontext] string getClassName(in jsval aObject);
 
   /**
    * Generate a content command event.
    *
    * Cannot be accessed from unprivileged context (not content-accessible)
    * Will throw a DOM security error if called without UniversalXPConnect
    * privileges.
    *
--- a/editor/libeditor/base/nsEditor.cpp
+++ b/editor/libeditor/base/nsEditor.cpp
@@ -1017,17 +1017,17 @@ nsEditor::SetShouldTxnSetSelection(bool 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsEditor::GetDocumentIsEmpty(bool *aDocumentIsEmpty)
 {
   *aDocumentIsEmpty = true;
 
-  nsIDOMElement *rootElement = GetRoot(); 
+  nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
   NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER); 
 
   bool hasChildNodes;
   nsresult res = rootElement->HasChildNodes(&hasChildNodes);
 
   *aDocumentIsEmpty = !hasChildNodes;
 
   return res;
@@ -1058,17 +1058,17 @@ NS_IMETHODIMP nsEditor::BeginningOfDocum
 
   // get the selection
   nsCOMPtr<nsISelection> selection;
   nsresult result = GetSelection(getter_AddRefs(selection));
   NS_ENSURE_SUCCESS(result, result);
   NS_ENSURE_TRUE(selection, NS_ERROR_NOT_INITIALIZED);
     
   // get the root element 
-  nsIDOMElement *rootElement = GetRoot(); 
+  nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
   NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER); 
   
   // find first editable thingy
   nsCOMPtr<nsIDOMNode> firstNode;
   result = GetFirstEditableNode(rootElement, address_of(firstNode));
   if (firstNode)
   {
     // if firstNode is text, set selection to beginning of the text node
@@ -1104,22 +1104,19 @@ nsEditor::EndOfDocument()
 
   // get selection 
   nsCOMPtr<nsISelection> selection; 
   res = GetSelection(getter_AddRefs(selection)); 
   NS_ENSURE_SUCCESS(res, res); 
   NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER); 
   
   // get the root element 
-  nsIDOMElement *rootElement = GetRoot(); 
-  NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER); 
-
-  nsCOMPtr<nsIDOMNode> node = do_QueryInterface(rootElement);
+  nsCOMPtr<nsIDOMNode> node = do_QueryInterface(GetRoot());
+  NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER); 
   nsCOMPtr<nsIDOMNode> child;
-  NS_ASSERTION(node, "Invalid root element");
 
   do {
     node->GetLastChild(getter_AddRefs(child));
 
     if (child) {
       if (IsContainer(child)) {
         node = child;
       } else {
@@ -1973,28 +1970,24 @@ nsEditor::GetPhonetic(nsAString& aPhonet
   else
     aPhonetic.Truncate(0);
 
   return NS_OK;
 }
 
 
 static nsresult
-GetEditorContentWindow(nsIDOMElement *aRoot, nsIWidget **aResult)
+GetEditorContentWindow(dom::Element *aRoot, nsIWidget **aResult)
 {
   NS_ENSURE_TRUE(aRoot && aResult, NS_ERROR_NULL_POINTER);
 
   *aResult = 0;
 
-  nsCOMPtr<nsIContent> content = do_QueryInterface(aRoot);
-
-  NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);
-
   // Not ref counted
-  nsIFrame *frame = content->GetPrimaryFrame();
+  nsIFrame *frame = aRoot->GetPrimaryFrame();
 
   NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
 
   *aResult = frame->GetNearestWidget();
   NS_ENSURE_TRUE(*aResult, NS_ERROR_FAILURE);
 
   NS_ADDREF(*aResult);
   return NS_OK;
@@ -2098,18 +2091,18 @@ nsEditor::GetComposing(bool* aResult)
 
 /* Non-interface, public methods */
 
 NS_IMETHODIMP
 nsEditor::GetRootElement(nsIDOMElement **aRootElement)
 {
   NS_ENSURE_ARG_POINTER(aRootElement);
   NS_ENSURE_TRUE(mRootElement, NS_ERROR_NOT_AVAILABLE);
-  *aRootElement = mRootElement;
-  NS_ADDREF(*aRootElement);
+  nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(mRootElement);
+  rootElement.forget(aRootElement);
   return NS_OK;
 }
 
 
 /** All editor operations which alter the doc should be prefaced
  *  with a call to StartOperation, naming the action and direction */
 NS_IMETHODIMP
 nsEditor::StartOperation(PRInt32 opID, nsIEditor::EDirection aDirection)
@@ -2170,22 +2163,20 @@ nsEditor::CloneAttributes(nsIDOMNode *aD
   nsCOMPtr<nsIDOMNamedNodeMap> destAttributes;
   destElement->GetAttributes(getter_AddRefs(destAttributes));
   NS_ENSURE_TRUE(sourceAttributes && destAttributes, NS_ERROR_FAILURE);
 
   nsAutoEditBatch beginBatching(this);
 
   // Use transaction system for undo only if destination
   //   is already in the document
-  nsIDOMElement *rootElement = GetRoot();
-  NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER);
-
+  nsCOMPtr<nsIDOMNode> p = aDestNode;
+  nsCOMPtr<nsIDOMNode> rootNode = do_QueryInterface(GetRoot());
+  NS_ENSURE_TRUE(rootNode, NS_ERROR_NULL_POINTER);
   bool destInBody = true;
-  nsCOMPtr<nsIDOMNode> rootNode = do_QueryInterface(rootElement);
-  nsCOMPtr<nsIDOMNode> p = aDestNode;
   while (p && p != rootNode)
   {
     nsCOMPtr<nsIDOMNode> tmp;
     if (NS_FAILED(p->GetParentNode(getter_AddRefs(tmp))) || !tmp)
     {
       destInBody = false;
       break;
     }
@@ -2287,34 +2278,35 @@ NS_IMETHODIMP nsEditor::InsertTextImpl(c
   // class to turn off txn selection updating.  Caller also turned on rules sniffing
   // if desired.
   
   nsresult res;
   NS_ENSURE_TRUE(aInOutNode && *aInOutNode && aInOutOffset && aDoc, NS_ERROR_NULL_POINTER);
   if (!mInIMEMode && aStringToInsert.IsEmpty()) return NS_OK;
   nsCOMPtr<nsIDOMText> nodeAsText = do_QueryInterface(*aInOutNode);
   if (!nodeAsText && IsPlaintextEditor()) {
+    nsCOMPtr<nsIDOMNode> rootNode = do_QueryInterface(GetRoot());
     // In some cases, aInOutNode is the anonymous DIV, and aInOutOffset is 0.
     // To avoid injecting unneeded text nodes, we first look to see if we have
     // one available.  In that case, we'll just adjust aInOutNode and aInOutOffset
     // accordingly.
-    if (*aInOutNode == GetRoot() && *aInOutOffset == 0) {
+    if (*aInOutNode == rootNode && *aInOutOffset == 0) {
       nsCOMPtr<nsIDOMNode> possibleTextNode;
       res = (*aInOutNode)->GetFirstChild(getter_AddRefs(possibleTextNode));
       if (NS_SUCCEEDED(res)) {
         nodeAsText = do_QueryInterface(possibleTextNode);
         if (nodeAsText) {
           *aInOutNode = possibleTextNode;
         }
       }
     }
     // In some other cases, aInOutNode is the anonymous DIV, and aInOutOffset points
     // to the terminating mozBR.  In that case, we'll adjust aInOutNode and aInOutOffset
     // to the preceding text node, if any.
-    if (!nodeAsText && *aInOutNode == GetRoot() && *aInOutOffset > 0) {
+    if (!nodeAsText && *aInOutNode == rootNode && *aInOutOffset > 0) {
       nsCOMPtr<nsIDOMNodeList> children;
       res = (*aInOutNode)->GetChildNodes(getter_AddRefs(children));
       if (NS_SUCCEEDED(res)) {
         nsCOMPtr<nsIDOMNode> possibleMozBRNode;
         children->Item(*aInOutOffset, getter_AddRefs(possibleMozBRNode));
         if (possibleMozBRNode && nsTextEditUtils::IsMozBR(possibleMozBRNode)) {
           nsCOMPtr<nsIDOMNode> possibleTextNode;
           res = children->Item(*aInOutOffset - 1, getter_AddRefs(possibleTextNode));
@@ -2358,17 +2350,17 @@ NS_IMETHODIMP nsEditor::InsertTextImpl(c
         res = nodeAsText->GetLength(&length);
         if (NS_SUCCEEDED(res)) {
           *aInOutOffset = PRInt32(length);
           *aInOutNode = previous;
         }
       } else {
         nsCOMPtr<nsIDOMNode> parent;
         (*aInOutNode)->GetParentNode(getter_AddRefs(parent));
-        if (parent == GetRoot()) {
+        if (parent == rootNode) {
           *aInOutNode = parent;
         }
       }
     }
   }
   PRInt32 offset = *aInOutOffset;
   if (mInIMEMode)
   {
@@ -2525,17 +2517,17 @@ nsresult nsEditor::InsertTextIntoTextNod
   return result;
 }
 
 
 NS_IMETHODIMP nsEditor::SelectEntireDocument(nsISelection *aSelection)
 {
   if (!aSelection) { return NS_ERROR_NULL_POINTER; }
 
-  nsIDOMElement *rootElement = GetRoot();
+  nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
   if (!rootElement) { return NS_ERROR_NOT_INITIALIZED; }
 
   return aSelection->SelectAllChildren(rootElement);
 }
 
 
 nsresult nsEditor::GetFirstEditableNode(nsIDOMNode *aRoot, nsCOMPtr<nsIDOMNode> *outFirstNode)
 {
@@ -3541,43 +3533,43 @@ nsEditor::TagCanContainTag(const nsAStri
   return true;
 }
 
 bool
 nsEditor::IsRootNode(nsIDOMNode *inNode)
 {
   NS_ENSURE_TRUE(inNode, false);
 
-  return inNode == GetRoot();
+  nsCOMPtr<nsIDOMNode> rootNode = do_QueryInterface(GetRoot());
+
+  return inNode == rootNode;
 }
 
 bool 
 nsEditor::IsRootNode(nsINode *inNode) 
 {
   NS_ENSURE_TRUE(inNode, false);
 
-  nsIDOMElement *rootElement = GetRoot();
-
-  nsCOMPtr<nsIDOMNode> node = do_QueryInterface(inNode);
-
-  return node == rootElement;
+  nsCOMPtr<nsINode> rootNode = GetRoot();
+
+  return inNode == rootNode;
 }
 
 bool 
 nsEditor::IsDescendantOfBody(nsIDOMNode *inNode) 
 {
   nsCOMPtr<nsINode> node = do_QueryInterface(inNode);
   return IsDescendantOfBody(node);
 }
 
 bool
 nsEditor::IsDescendantOfBody(nsINode *inNode)
 {
   NS_ENSURE_TRUE(inNode, false);
-  nsCOMPtr<nsIContent> root = do_QueryInterface(GetRoot());
+  nsCOMPtr<nsIContent> root = GetRoot();
   NS_ENSURE_TRUE(root, false);
 
   return nsContentUtils::ContentIsDescendantOf(inNode, root);
 }
 
 bool 
 nsEditor::IsContainer(nsIDOMNode *aNode)
 {
@@ -5144,17 +5136,17 @@ nsEditor::HandleInlineSpellCheck(PRInt32
                                                        aStartOffset,
                                                        aEndNode,
                                                        aEndOffset) : NS_OK;
 }
 
 already_AddRefed<nsIContent>
 nsEditor::FindSelectionRoot(nsINode *aNode)
 {
-  nsCOMPtr<nsIContent> rootContent = do_QueryInterface(GetRoot());
+  nsCOMPtr<nsIContent> rootContent = GetRoot();
   return rootContent.forget();
 }
 
 nsresult
 nsEditor::InitializeSelection(nsIDOMEventTarget* aFocusEventTarget)
 {
   nsCOMPtr<nsINode> targetNode = do_QueryInterface(aFocusEventTarget);
   NS_ENSURE_TRUE(targetNode, NS_ERROR_INVALID_ARG);
@@ -5213,17 +5205,17 @@ nsEditor::InitializeSelection(nsIDOMEven
     if (rangeCount == 0) {
       BeginningOfDocument();
     }
   }
 
   return NS_OK;
 }
 
-nsIDOMElement *
+dom::Element *
 nsEditor::GetRoot()
 {
   if (!mRootElement)
   {
     nsCOMPtr<nsIDOMElement> root;
 
     // Let GetRootElement() do the work
     GetRootElement(getter_AddRefs(root));
@@ -5231,28 +5223,24 @@ nsEditor::GetRoot()
 
   return mRootElement;
 }
 
 nsresult
 nsEditor::DetermineCurrentDirection()
 {
   // Get the current root direction from its frame
-  nsIDOMElement *rootElement = GetRoot();
-
-  nsresult rv;
+  dom::Element *rootElement = GetRoot();
 
   // If we don't have an explicit direction, determine our direction
   // from the content's direction
   if (!(mFlags & (nsIPlaintextEditor::eEditorLeftToRight |
                   nsIPlaintextEditor::eEditorRightToLeft))) {
-    nsCOMPtr<nsIContent> content = do_QueryInterface(rootElement, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsIFrame* frame = content->GetPrimaryFrame();
+
+    nsIFrame* frame = rootElement->GetPrimaryFrame();
     NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
 
     // Set the flag here, to enable us to use the same code path below.
     // It will be flipped before returning from the function.
     if (frame->GetStyleVisibility()->mDirection == NS_STYLE_DIRECTION_RTL) {
       mFlags |= nsIPlaintextEditor::eEditorRightToLeft;
     } else {
       mFlags |= nsIPlaintextEditor::eEditorLeftToRight;
@@ -5261,63 +5249,61 @@ nsEditor::DetermineCurrentDirection()
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsEditor::SwitchTextDirection()
 {
   // Get the current root direction from its frame
-  nsIDOMElement *rootElement = GetRoot();
-
+  dom::Element *rootElement = GetRoot();
   nsresult rv = DetermineCurrentDirection();
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Apply the opposite direction
   if (mFlags & nsIPlaintextEditor::eEditorRightToLeft) {
     NS_ASSERTION(!(mFlags & nsIPlaintextEditor::eEditorLeftToRight),
                  "Unexpected mutually exclusive flag");
     mFlags &= ~nsIPlaintextEditor::eEditorRightToLeft;
     mFlags |= nsIPlaintextEditor::eEditorLeftToRight;
-    rv = rootElement->SetAttribute(NS_LITERAL_STRING("dir"), NS_LITERAL_STRING("ltr"));
+    rv = rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, NS_LITERAL_STRING("ltr"), true);
   } else if (mFlags & nsIPlaintextEditor::eEditorLeftToRight) {
     NS_ASSERTION(!(mFlags & nsIPlaintextEditor::eEditorRightToLeft),
                  "Unexpected mutually exclusive flag");
     mFlags |= nsIPlaintextEditor::eEditorRightToLeft;
     mFlags &= ~nsIPlaintextEditor::eEditorLeftToRight;
-    rv = rootElement->SetAttribute(NS_LITERAL_STRING("dir"), NS_LITERAL_STRING("rtl"));
+    rv = rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, NS_LITERAL_STRING("rtl"), true);
   }
 
   return rv;
 }
 
 void
 nsEditor::SwitchTextDirectionTo(PRUint32 aDirection)
 {
   // Get the current root direction from its frame
-  nsIDOMElement *rootElement = GetRoot();
-
+  dom::Element *rootElement = GetRoot();
   nsresult rv = DetermineCurrentDirection();
   NS_ENSURE_SUCCESS(rv, );
 
   // Apply the requested direction
   if (aDirection == nsIPlaintextEditor::eEditorLeftToRight &&
       (mFlags & nsIPlaintextEditor::eEditorRightToLeft)) {
     NS_ASSERTION(!(mFlags & nsIPlaintextEditor::eEditorLeftToRight),
                  "Unexpected mutually exclusive flag");
     mFlags &= ~nsIPlaintextEditor::eEditorRightToLeft;
     mFlags |= nsIPlaintextEditor::eEditorLeftToRight;
-    rootElement->SetAttribute(NS_LITERAL_STRING("dir"), NS_LITERAL_STRING("ltr"));
+    rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, NS_LITERAL_STRING("ltr"), true);
   } else if (aDirection == nsIPlaintextEditor::eEditorRightToLeft &&
              (mFlags & nsIPlaintextEditor::eEditorLeftToRight)) {
     NS_ASSERTION(!(mFlags & nsIPlaintextEditor::eEditorRightToLeft),
                  "Unexpected mutually exclusive flag");
     mFlags |= nsIPlaintextEditor::eEditorRightToLeft;
     mFlags &= ~nsIPlaintextEditor::eEditorLeftToRight;
-    rootElement->SetAttribute(NS_LITERAL_STRING("dir"), NS_LITERAL_STRING("rtl"));
+    rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, NS_LITERAL_STRING("rtl"), true);
   }
 }
 
 #if DEBUG_JOE
 void
 nsEditor::DumpNode(nsIDOMNode *aNode, PRInt32 indent)
 {
   PRInt32 i;
--- a/editor/libeditor/base/nsEditor.h
+++ b/editor/libeditor/base/nsEditor.h
@@ -646,17 +646,17 @@ public:
                                     nsIDOMNode *aStartNode,
                                     PRInt32 aStartOffset,
                                     nsIDOMNode *aEndNode,
                                     PRInt32 aEndOffset);
 
   virtual already_AddRefed<nsIDOMEventTarget> GetDOMEventTarget() = 0;
 
   // Fast non-refcounting editor root element accessor
-  nsIDOMElement *GetRoot();
+  mozilla::dom::Element *GetRoot();
 
   // Accessor methods to flags
   bool IsPlaintextEditor() const
   {
     return (mFlags & nsIPlaintextEditor::eEditorPlaintextMask) != 0;
   }
 
   bool IsSingleLineEditor() const
@@ -758,18 +758,18 @@ public:
 
   // This method has to be called by nsEditorEventListener::Focus.
   // All actions that have to be done when the editor is focused needs to be
   // added here.
   void OnFocus(nsIDOMEventTarget* aFocusEventTarget);
 
 protected:
 
-  PRUint32        mModCount;		// number of modifications (for undo/redo stack)
-  PRUint32        mFlags;		// behavior flags. See nsIPlaintextEditor.idl for the flags we use.
+  PRUint32        mModCount;     // number of modifications (for undo/redo stack)
+  PRUint32        mFlags;        // behavior flags. See nsIPlaintextEditor.idl for the flags we use.
 
   nsWeakPtr       mSelConWeak;   // weak reference to the nsISelectionController
   PRInt32         mUpdateCount;
   nsIViewManager::UpdateViewBatch mBatch;
 
   // Spellchecking
   enum Tristate {
     eTriUnset,
@@ -780,17 +780,17 @@ protected:
 
   nsCOMPtr<nsITransactionManager> mTxnMgr;
   nsWeakPtr         mPlaceHolderTxn;     // weak reference to placeholder for begin/end batch purposes
   nsIAtom          *mPlaceHolderName;    // name of placeholder transaction
   PRInt32           mPlaceHolderBatch;   // nesting count for batching
   nsSelectionState *mSelState;           // saved selection state for placeholder txn batching
   nsSelectionState  mSavedSel;           // cached selection for nsAutoSelectionReset
   nsRangeUpdater    mRangeUpdater;       // utility class object for maintaining preserved ranges
-  nsCOMPtr<nsIDOMElement> mRootElement;    // cached root node
+  nsCOMPtr<mozilla::dom::Element> mRootElement;   // cached root node
   PRInt32           mAction;             // the current editor action
   EDirection        mDirection;          // the current direction of editor action
   
   // data necessary to build IME transactions
   nsCOMPtr<nsIPrivateTextRangeList> mIMETextRangeList; // IME special selection ranges
   nsCOMPtr<nsIDOMCharacterData>     mIMETextNode;      // current IME text node
   PRUint32                          mIMETextOffset;    // offset in text node where IME comp string begins
   PRUint32                          mIMEBufferLength;  // current length of IME comp string
--- a/editor/libeditor/html/nsHTMLCSSUtils.cpp
+++ b/editor/libeditor/html/nsHTMLCSSUtils.cpp
@@ -1396,22 +1396,8 @@ nsresult
 nsHTMLCSSUtils::SetCSSPropertyPixels(nsIDOMElement * aElement,
                                      const nsAString & aProperty,
                                      PRInt32 aIntValue)
 {
   nsAutoString s;
   s.AppendInt(aIntValue);
   return SetCSSProperty(aElement, aProperty, s + NS_LITERAL_STRING("px"));
 }
-
-nsresult
-nsHTMLCSSUtils::RemoveCSSProperty(nsIDOMElement * aElement,
-                                  const nsAString & aProperty)
-{
-  nsCOMPtr<nsIDOMCSSStyleDeclaration> cssDecl;
-  PRUint32 length;
-  nsresult res = GetInlineStyles(aElement, getter_AddRefs(cssDecl), &length);
-  if (NS_FAILED(res) || !cssDecl) return res;
-
-  nsAutoString returnString;
-  return cssDecl->RemoveProperty(aProperty, returnString);
-}
-
--- a/editor/libeditor/html/nsHTMLCSSUtils.h
+++ b/editor/libeditor/html/nsHTMLCSSUtils.h
@@ -134,18 +134,16 @@ public:
     * @param aValue         [IN] a string containing the new value of the CSS property
     */
   nsresult    SetCSSProperty(nsIDOMElement * aElement,
                              const nsAString & aProperty,
                              const nsAString & aValue);
   nsresult    SetCSSPropertyPixels(nsIDOMElement * aElement,
                                    const nsAString & aProperty,
                                    PRInt32 aIntValue);
-  nsresult    RemoveCSSProperty(nsIDOMElement * aElement,
-                                const nsAString & aProperty);
 
   /** gets the specified/computed style value of a CSS property for a given node (or its element
     * ancestor if it is not an element)
     *
     * @param aNode          [IN] a DOM node
     * @param aProperty      [IN] an atom containing the CSS property to get
     * @param aPropertyValue [OUT] the retrieved value of the property
     */
--- a/editor/libeditor/html/nsHTMLEditRules.cpp
+++ b/editor/libeditor/html/nsHTMLEditRules.cpp
@@ -76,16 +76,17 @@
 #include "nsUnicharUtils.h"
 
 #include "nsFrameSelection.h"
 #include "nsContentUtils.h"
 #include "nsTArray.h"
 #include "nsIHTMLDocument.h"
 
 #include "mozilla/Preferences.h"
+#include "mozilla/dom/Element.h"
 
 using namespace mozilla;
 
 //const static char* kMOZEditorBogusNodeAttr="MOZ_EDITOR_BOGUS_NODE";
 //const static char* kMOZEditorBogusNodeValue="TRUE";
 
 enum
 {
@@ -251,17 +252,17 @@ nsHTMLEditRules::Init(nsPlaintextEditor 
   // XXX Why was this pref designed as a string and not bool?
   mReturnInEmptyLIKillsList = !returnInEmptyLIKillsList.EqualsLiteral("false");
 
   // make a utility range for use by the listenter
   mUtilRange = do_CreateInstance("@mozilla.org/content/range;1");
   NS_ENSURE_TRUE(mUtilRange, NS_ERROR_NULL_POINTER);
    
   // set up mDocChangeRange to be whole doc
-  nsIDOMElement *rootElem = mHTMLEditor->GetRoot();
+  nsCOMPtr<nsIDOMElement> rootElem = do_QueryInterface(mHTMLEditor->GetRoot());
   if (rootElem)
   {
     // temporarily turn off rules sniffing
     nsAutoLockRulesSniffing lockIt((nsTextEditRules*)this);
     if (!mDocChangeRange)
     {
       mDocChangeRange = do_CreateInstance("@mozilla.org/content/range;1");
       NS_ENSURE_TRUE(mDocChangeRange, NS_ERROR_NULL_POINTER);
@@ -800,17 +801,17 @@ nsHTMLEditRules::GetAlignment(bool *aMix
 
   // get selection
   nsCOMPtr<nsISelection>selection;
   nsresult res = mHTMLEditor->GetSelection(getter_AddRefs(selection));
   NS_ENSURE_SUCCESS(res, res);
 
   // get selection location
   nsCOMPtr<nsIDOMNode> parent;
-  nsIDOMElement *rootElem = mHTMLEditor->GetRoot();
+  nsCOMPtr<nsIDOMElement> rootElem = do_QueryInterface(mHTMLEditor->GetRoot());
   NS_ENSURE_TRUE(rootElem, NS_ERROR_FAILURE);
 
   PRInt32 offset, rootOffset;
   res = nsEditor::GetNodeLocation(rootElem, address_of(parent), &rootOffset);
   NS_ENSURE_SUCCESS(res, res);
   res = mHTMLEditor->GetStartNodeAndOffset(selection, getter_AddRefs(parent), &offset);
   NS_ENSURE_SUCCESS(res, res);
 
@@ -1007,23 +1008,20 @@ nsHTMLEditRules::GetIndentState(bool *aC
   
   if (!*aCanOutdent)
   {
     // if we haven't found something to outdent yet, also check the parents
     // of selection endpoints.  We might have a blockquote or list item 
     // in the parent hierarchy.
     
     // gather up info we need for test
-    nsCOMPtr<nsIDOMNode> parent, tmp, root;
-    nsIDOMElement *rootElem = mHTMLEditor->GetRoot();
-    NS_ENSURE_TRUE(rootElem, NS_ERROR_NULL_POINTER);
+    nsCOMPtr<nsIDOMNode> parent, tmp, root = do_QueryInterface(mHTMLEditor->GetRoot());
+    NS_ENSURE_TRUE(root, NS_ERROR_NULL_POINTER);
     nsCOMPtr<nsISelection> selection;
     PRInt32 selOffset;
-    root = do_QueryInterface(rootElem);
-    NS_ENSURE_TRUE(root, NS_ERROR_NO_INTERFACE);
     res = mHTMLEditor->GetSelection(getter_AddRefs(selection));
     NS_ENSURE_SUCCESS(res, res);
     NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
     
     // test start parent hierarchy
     res = mHTMLEditor->GetStartNodeAndOffset(selection, getter_AddRefs(parent), &selOffset);
     NS_ENSURE_SUCCESS(res, res);
     while (parent && (parent!=root))
@@ -1103,17 +1101,17 @@ nsHTMLEditRules::GetParagraphState(bool 
     res = mHTMLEditor->GetStartNodeAndOffset(selection, getter_AddRefs(selNode), &selOffset);
     NS_ENSURE_SUCCESS(res, res);
     NS_ENSURE_TRUE(selNode, NS_ERROR_NULL_POINTER);
     arrayOfNodes.AppendObject(selNode);
     listCount = 1;
   }
 
   // remember root node
-  nsIDOMElement *rootElem = mHTMLEditor->GetRoot();
+  nsCOMPtr<nsIDOMElement> rootElem = do_QueryInterface(mHTMLEditor->GetRoot());
   NS_ENSURE_TRUE(rootElem, NS_ERROR_NULL_POINTER);
 
   // loop through the nodes in selection and examine their paragraph format
   for (i=listCount-1; i>=0; i--)
   {
     nsCOMPtr<nsIDOMNode> curNode = arrayOfNodes[i];
     nsAutoString format;
     // if it is a known format node we have it easy
@@ -7773,19 +7771,18 @@ nsHTMLEditRules::AdjustSelection(nsISele
   else theblock = mHTMLEditor->GetBlockNodeParent(selNode);
   if (theblock && mHTMLEditor->IsEditable(theblock)) {
     bool bIsEmptyNode;
     res = mHTMLEditor->IsEmptyNode(theblock, &bIsEmptyNode, false, false);
     NS_ENSURE_SUCCESS(res, res);
     // check if br can go into the destination node
     if (bIsEmptyNode && mHTMLEditor->CanContainTag(selNode, NS_LITERAL_STRING("br")))
     {
-      nsIDOMElement *rootElement = mHTMLEditor->GetRoot();
-      NS_ENSURE_TRUE(rootElement, NS_ERROR_FAILURE);
-      nsCOMPtr<nsIDOMNode> rootNode(do_QueryInterface(rootElement));
+      nsCOMPtr<nsIDOMNode> rootNode = do_QueryInterface(mHTMLEditor->GetRoot());
+      NS_ENSURE_TRUE(rootNode, NS_ERROR_FAILURE);
       if (selNode == rootNode)
       {
         // Our root node is completely empty. Don't add a <br> here.
         // AfterEditInner() will add one for us when it calls
         // CreateBogusNodeIfNeeded()!
         return NS_OK;
       }
 
@@ -8354,17 +8351,17 @@ nsHTMLEditRules::RemoveListStructure(nsI
 
 
 nsresult 
 nsHTMLEditRules::ConfirmSelectionInBody()
 {
   nsresult res = NS_OK;
 
   // get the body  
-  nsIDOMElement *rootElement = mHTMLEditor->GetRoot();
+  nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(mHTMLEditor->GetRoot());
   NS_ENSURE_TRUE(rootElement, NS_ERROR_UNEXPECTED);
 
   // get the selection
   nsCOMPtr<nsISelection>selection;
   res = mHTMLEditor->GetSelection(getter_AddRefs(selection));
   NS_ENSURE_SUCCESS(res, res);
   
   // get the selection start location
--- a/editor/libeditor/html/nsHTMLEditor.cpp
+++ b/editor/libeditor/html/nsHTMLEditor.cpp
@@ -376,38 +376,39 @@ nsHTMLEditor::GetRootElement(nsIDOMEleme
     return nsEditor::GetRootElement(aRootElement);
   }
 
   *aRootElement = nsnull;
 
   // Use the HTML documents body element as the editor root if we didn't
   // get a root element during initialization.
 
+  nsCOMPtr<nsIDOMElement> rootElement; 
   nsCOMPtr<nsIDOMHTMLElement> bodyElement; 
   nsresult rv = GetBodyElement(getter_AddRefs(bodyElement));
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (bodyElement) {
-    mRootElement = bodyElement;
+    rootElement = bodyElement;
   } else {
     // If there is no HTML body element,
     // we should use the document root element instead.
     nsCOMPtr<nsIDOMDocument> doc = do_QueryReferent(mDocWeak);
     NS_ENSURE_TRUE(doc, NS_ERROR_NOT_INITIALIZED);
 
-    rv = doc->GetDocumentElement(getter_AddRefs(mRootElement));
+    rv = doc->GetDocumentElement(getter_AddRefs(rootElement));
     NS_ENSURE_SUCCESS(rv, rv);
     // Document can have no elements
-    if (!mRootElement) {
+    if (!rootElement) {
       return NS_ERROR_NOT_AVAILABLE;
     }
   }
 
-  *aRootElement = mRootElement;
-  NS_ADDREF(*aRootElement);
+  mRootElement = do_QueryInterface(rootElement);
+  rootElement.forget(aRootElement);
 
   return NS_OK;
 }
 
 already_AddRefed<nsIContent>
 nsHTMLEditor::FindSelectionRoot(nsINode *aNode)
 {
   NS_PRECONDITION(aNode->IsNodeOfType(nsINode::eDOCUMENT) ||
@@ -539,17 +540,17 @@ nsHTMLEditor::BeginningOfDocument()
 
   // get the selection
   nsCOMPtr<nsISelection> selection;
   nsresult res = GetSelection(getter_AddRefs(selection));
   NS_ENSURE_SUCCESS(res, res);
   NS_ENSURE_TRUE(selection, NS_ERROR_NOT_INITIALIZED);
 
   // Get the root element.
-  nsIDOMElement *rootElement = GetRoot();
+  nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
   if (!rootElement) {
     NS_WARNING("GetRoot() returned a null pointer (mRootElement is null)");
     return NS_OK;
   }
 
   // find first editable thingy
   bool done = false;
   nsCOMPtr<nsIDOMNode> curNode(rootElement), selNode;
@@ -964,165 +965,16 @@ nsHTMLEditor::GetBlockNodeParent(nsIDOMN
       break;
 
     p = tmp;
   }
   return p.forget();
 }
 
 ///////////////////////////////////////////////////////////////////////////
-// GetBlockSection: return leftmost/rightmost nodes in aChild's block
-//               
-nsresult
-nsHTMLEditor::GetBlockSection(nsIDOMNode *aChild,
-                              nsIDOMNode **aLeftNode, 
-                              nsIDOMNode **aRightNode) 
-{
-  nsresult result = NS_OK;
-  if (!aChild || !aLeftNode || !aRightNode) {return NS_ERROR_NULL_POINTER;}
-  *aLeftNode = aChild;
-  *aRightNode = aChild;
-
-  nsCOMPtr<nsIDOMNode>sibling;
-  result = aChild->GetPreviousSibling(getter_AddRefs(sibling));
-  while ((NS_SUCCEEDED(result)) && sibling)
-  {
-    bool isBlock;
-    NodeIsBlockStatic(sibling, &isBlock);
-    if (isBlock)
-    {
-      nsCOMPtr<nsIDOMCharacterData>nodeAsText = do_QueryInterface(sibling);
-      if (!nodeAsText) {
-        break;
-      }
-      // XXX: needs some logic to work for other leaf nodes besides text!
-    }
-    *aLeftNode = sibling;
-    result = (*aLeftNode)->GetPreviousSibling(getter_AddRefs(sibling)); 
-  }
-  NS_ADDREF((*aLeftNode));
-  // now do the right side
-  result = aChild->GetNextSibling(getter_AddRefs(sibling));
-  while ((NS_SUCCEEDED(result)) && sibling)
-  {
-    bool isBlock;
-    NodeIsBlockStatic(sibling, &isBlock);
-    if (isBlock) 
-    {
-      nsCOMPtr<nsIDOMCharacterData>nodeAsText = do_QueryInterface(sibling);
-      if (!nodeAsText) {
-        break;
-      }
-    }
-    *aRightNode = sibling;
-    result = (*aRightNode)->GetNextSibling(getter_AddRefs(sibling)); 
-  }
-  NS_ADDREF((*aRightNode));
-
-  return result;
-}
-
-
-///////////////////////////////////////////////////////////////////////////
-// GetBlockSectionsForRange: return list of block sections that intersect 
-//                           this range
-nsresult
-nsHTMLEditor::GetBlockSectionsForRange(nsIDOMRange *aRange,
-                                       nsCOMArray<nsIDOMRange>& aSections) 
-{
-  if (!aRange) {return NS_ERROR_NULL_POINTER;}
-
-  nsresult result;
-  nsCOMPtr<nsIContentIterator>iter =
-    do_CreateInstance("@mozilla.org/content/post-content-iterator;1", &result);
-  if (NS_FAILED(result) || !iter) {
-    return result;
-  }
-  nsCOMPtr<nsIDOMRange> lastRange;
-  iter->Init(aRange);
-  while (iter->IsDone())
-  {
-    nsCOMPtr<nsIContent> currentContent =
-      do_QueryInterface(iter->GetCurrentNode());
-
-    nsCOMPtr<nsIDOMNode> currentNode = do_QueryInterface(currentContent);
-    if (currentNode)
-    {
-      // <BR> divides block content ranges.  We can achieve this by nulling out lastRange
-      if (currentContent->Tag() == nsEditProperty::br)
-      {
-        lastRange = nsnull;
-      }
-      else
-      {
-        bool isNotInlineOrText;
-        result = NodeIsBlockStatic(currentNode, &isNotInlineOrText);
-        if (isNotInlineOrText)
-        {
-          PRUint16 nodeType;
-          currentNode->GetNodeType(&nodeType);
-          if (nsIDOMNode::TEXT_NODE == nodeType) {
-            isNotInlineOrText = true;
-          }
-        }
-        if (!isNotInlineOrText) {
-          nsCOMPtr<nsIDOMNode> leftNode;
-          nsCOMPtr<nsIDOMNode> rightNode;
-          result = GetBlockSection(currentNode,
-                                   getter_AddRefs(leftNode),
-                                   getter_AddRefs(rightNode));
-          if ((NS_SUCCEEDED(result)) && leftNode && rightNode) {
-            // Add range to the list if it doesn't overlap with the previous
-            // range.
-            bool addRange = true;
-            if (lastRange)
-            {
-              nsCOMPtr<nsIDOMNode> lastStartNode;
-              lastRange->GetStartContainer(getter_AddRefs(lastStartNode));
-              nsCOMPtr<nsIDOMNode> blockParentNodeOfLastStartNode =
-                GetBlockNodeParent(lastStartNode);
-              nsCOMPtr<nsIDOMElement> blockParentOfLastStartNode =
-                do_QueryInterface(blockParentNodeOfLastStartNode);
-              if (blockParentOfLastStartNode)
-              {
-                nsCOMPtr<nsIDOMNode> blockParentNodeOfLeftNode =
-                  GetBlockNodeParent(leftNode);
-                nsCOMPtr<nsIDOMElement> blockParentOfLeftNode =
-                  do_QueryInterface(blockParentNodeOfLeftNode);
-                if (blockParentOfLeftNode &&
-                    blockParentOfLastStartNode == blockParentOfLeftNode) {
-                  addRange = false;
-                }
-              }
-            }
-            if (addRange) {
-              nsCOMPtr<nsIDOMRange> range =
-                   do_CreateInstance("@mozilla.org/content/range;1", &result);
-              if ((NS_SUCCEEDED(result)) && range) {
-                // Initialize the range.
-                range->SetStart(leftNode, 0);
-                range->SetEnd(rightNode, 0);
-                aSections.AppendObject(range);
-                lastRange = do_QueryInterface(range);
-              }
-            }        
-          }
-        }
-      }
-    }
-    /* do not check result here, and especially do not return the result code.
-     * we rely on iter->IsDone to tell us when the iteration is complete
-     */
-    iter->Next();
-  }
-  return result;
-}
-
-
-///////////////////////////////////////////////////////////////////////////
 // NextNodeInBlock: gets the next/prev node in the block, if any.  Next node
 //                  must be an element or text node, others are ignored
 already_AddRefed<nsIDOMNode>
 nsHTMLEditor::NextNodeInBlock(nsIDOMNode *aNode, IterDirection aDir)
 {
   NS_ENSURE_TRUE(aNode, nsnull);
 
   nsresult rv;
@@ -1804,18 +1656,17 @@ NS_IMETHODIMP
 nsHTMLEditor::RebuildDocumentFromSource(const nsAString& aSourceString)
 {
   ForceCompositionEnd();
 
   nsCOMPtr<nsISelection>selection;
   nsresult res = GetSelection(getter_AddRefs(selection));
   NS_ENSURE_SUCCESS(res, res);
 
-  nsIDOMElement *bodyElement = GetRoot();
-  NS_ENSURE_SUCCESS(res, res);
+  nsCOMPtr<nsIDOMElement> bodyElement = do_QueryInterface(GetRoot());
   NS_ENSURE_TRUE(bodyElement, NS_ERROR_NULL_POINTER);
 
   // Find where the <body> tag starts.
   nsReadingIterator<PRUnichar> beginbody;
   nsReadingIterator<PRUnichar> endbody;
   aSourceString.BeginReading(beginbody);
   aSourceString.EndReading(endbody);
   bool foundbody = CaseInsensitiveFindInReadable(NS_LITERAL_STRING("<body"),
@@ -2447,20 +2298,20 @@ nsHTMLEditor::GetHTMLBackgroundColorStat
     // from nested cells/tables, so search up parent chain
     nsCOMPtr<nsIDOMNode> parentNode;
     res = element->GetParentNode(getter_AddRefs(parentNode));
     NS_ENSURE_SUCCESS(res, res);
     element = do_QueryInterface(parentNode);
   }
 
   // If no table or cell found, get page body
-  element = GetRoot();
-  NS_ENSURE_TRUE(element, NS_ERROR_NULL_POINTER);
-
-  return element->GetAttribute(styleName, aOutColor);
+  mozilla::dom::Element *bodyElement = GetRoot();
+  NS_ENSURE_TRUE(bodyElement, NS_ERROR_NULL_POINTER);
+
+  return bodyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::bgcolor, aOutColor);
 }
 
 NS_IMETHODIMP 
 nsHTMLEditor::GetListState(bool *aMixed, bool *aOL, bool *aUL, bool *aDL)
 {
   if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
   NS_ENSURE_TRUE(aMixed && aOL && aUL && aDL, NS_ERROR_NULL_POINTER);
   nsHTMLEditRules* htmlRules = static_cast<nsHTMLEditRules*>(mRules.get());
@@ -3387,17 +3238,17 @@ nsHTMLEditor::SetHTMLBackgroundColor(con
           GetNextSelectedCell(nsnull, getter_AddRefs(cell));
         };
         return res;
       }
     }
     // If we failed to find a cell, fall through to use originally-found element
   } else {
     // No table element -- set the background color on the body tag
-    element = GetRoot();
+    element = do_QueryInterface(GetRoot());
     NS_ENSURE_TRUE(element, NS_ERROR_NULL_POINTER);
   }
   // Use the editor method that goes through the transaction system
   if (setColor)
     res = SetAttribute(element, bgcolor, aColor);
   else
     res = RemoveAttribute(element, bgcolor);
 
@@ -3406,18 +3257,17 @@ nsHTMLEditor::SetHTMLBackgroundColor(con
 
 NS_IMETHODIMP nsHTMLEditor::SetBodyAttribute(const nsAString& aAttribute, const nsAString& aValue)
 {
   // TODO: Check selection for Cell, Row, Column or table and do color on appropriate level
 
   NS_ASSERTION(mDocWeak, "Missing Editor DOM Document");
   
   // Set the background color attribute on the body tag
-  nsIDOMElement *bodyElement = GetRoot();
-
+  nsCOMPtr<nsIDOMElement> bodyElement = do_QueryInterface(GetRoot());
   NS_ENSURE_TRUE(bodyElement, NS_ERROR_NULL_POINTER);
 
   // Use the editor method that goes through the transaction system
   return SetAttribute(bodyElement, aAttribute, aValue);
 }
 
 NS_IMETHODIMP
 nsHTMLEditor::GetLinkedObjects(nsISupportsArray** aNodeList)
@@ -3875,17 +3725,17 @@ nsHTMLEditor::ContentRemoved(nsIDocument
 
 
 /* This routine examines aNode and it's ancestors looking for any node which has the
    -moz-user-select: all style lit.  Return the highest such ancestor.  */
 already_AddRefed<nsIDOMNode>
 nsHTMLEditor::FindUserSelectAllNode(nsIDOMNode* aNode)
 {
   nsCOMPtr<nsIDOMNode> node = aNode;
-  nsIDOMElement *root = GetRoot();
+  nsCOMPtr<nsIDOMElement> root = do_QueryInterface(GetRoot());
   if (!nsEditorUtils::IsDescendantOf(aNode, root))
     return nsnull;
 
   nsCOMPtr<nsIDOMNode> resultNode;  // starts out empty
   nsAutoString mozUserSelectValue;
   while (node)
   {
     // retrieve the computed style of -moz-user-select for node
@@ -4140,17 +3990,17 @@ NS_IMETHODIMP
 nsHTMLEditor::SelectEntireDocument(nsISelection *aSelection)
 {
   if (!aSelection || !mRules) { return NS_ERROR_NULL_POINTER; }
   
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> kungFuDeathGrip(mRules);
 
   // get editor root node
-  nsIDOMElement *rootElement = GetRoot();
+  nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
   
   // is doc empty?
   bool bDocIsEmpty;
   nsresult res = mRules->DocumentIsEmpty(&bDocIsEmpty);
   NS_ENSURE_SUCCESS(res, res);
     
   if (bDocIsEmpty)
   {
@@ -4185,17 +4035,19 @@ nsHTMLEditor::SelectAll()
   
   // If the anchor content has independent selection, we never need to explicitly
   // select its children.
   if (anchorContent->HasIndependentSelection()) {
     nsCOMPtr<nsISelectionPrivate> selPriv = do_QueryInterface(selection);
     NS_ENSURE_TRUE(selPriv, NS_ERROR_UNEXPECTED);
     rv = selPriv->SetAncestorLimiter(nsnull);
     NS_ENSURE_SUCCESS(rv, rv);
-    return selection->SelectAllChildren(mRootElement);
+    nsCOMPtr<nsIDOMNode> rootElement = do_QueryInterface(mRootElement, &rv);
+    NS_ENSURE_SUCCESS(rv, rv);
+    return selection->SelectAllChildren(rootElement);
   }
 
   nsCOMPtr<nsIPresShell> ps = GetPresShell();
   nsIContent *rootContent = anchorContent->GetSelectionRootContent(ps);
   NS_ENSURE_TRUE(rootContent, NS_ERROR_UNEXPECTED);
 
   nsCOMPtr<nsIDOMNode> rootElement = do_QueryInterface(rootContent, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -4476,17 +4328,17 @@ nsHTMLEditor::CollapseAdjacentTextNodes(
   }
 
   return result;
 }
 
 NS_IMETHODIMP 
 nsHTMLEditor::SetSelectionAtDocumentStart(nsISelection *aSelection)
 {
-  nsIDOMElement *rootElement = GetRoot();  
+  nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
   NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER);
 
   return aSelection->Collapse(rootElement,0);
 }
 
 
 ///////////////////////////////////////////////////////////////////////////
 // RemoveBlockContainer: remove inNode, reparenting it's children into their
--- a/editor/libeditor/html/nsHTMLEditor.h
+++ b/editor/libeditor/html/nsHTMLEditor.h
@@ -272,48 +272,16 @@ public:
   /* miscellaneous */
   // This sets background on the appropriate container element (table, cell,)
   //   or calls into nsTextEditor to set the page background
   NS_IMETHOD SetCSSBackgroundColor(const nsAString& aColor);
   NS_IMETHOD SetHTMLBackgroundColor(const nsAString& aColor);
 
   /* ------------ Block methods moved from nsEditor -------------- */
   static already_AddRefed<nsIDOMNode> GetBlockNodeParent(nsIDOMNode *aNode);
-  /** Determines the bounding nodes for the block section containing aNode.
-    * The calculation is based on some nodes intrinsically being block elements
-    * acording to HTML.  Style sheets are not considered in this calculation.
-    * <BR> tags separate block content sections.  So the HTML markup:
-    * <PRE>
-    *      <P>text1<BR>text2<B>text3</B></P>
-    * </PRE>
-    * contains two block content sections.  The first has the text node "text1"
-    * for both endpoints.  The second has "text2" as the left endpoint and
-    * "text3" as the right endpoint.
-    * Notice that offsets aren't required, only leaf nodes.  Offsets are implicit.
-    *
-    * @param aNode      the block content returned includes aNode
-    * @param aLeftNode  [OUT] the left endpoint of the block content containing aNode
-    * @param aRightNode [OUT] the right endpoint of the block content containing aNode
-    *
-    */
-  static nsresult GetBlockSection(nsIDOMNode  *aNode,
-                                  nsIDOMNode **aLeftNode, 
-                                  nsIDOMNode **aRightNode);
-
-  /** Compute the set of block sections in a given range.
-    * A block section is the set of (leftNode, rightNode) pairs given
-    * by GetBlockSection.  The set is computed by computing the 
-    * block section for every leaf node in the range and throwing 
-    * out duplicates.
-    *
-    * @param aRange     The range to compute block sections for.
-    * @param aSections  Allocated storage for the resulting set, stored as nsIDOMRanges.
-    */
-  static nsresult GetBlockSectionsForRange(nsIDOMRange      *aRange, 
-                                           nsCOMArray<nsIDOMRange>& aSections);
 
   static already_AddRefed<nsIDOMNode> NextNodeInBlock(nsIDOMNode *aNode, IterDirection aDir);
   nsresult IsNextCharWhitespace(nsIDOMNode *aParentNode, 
                                 PRInt32 aOffset, 
                                 bool *outIsSpace, 
                                 bool *outIsNBSP,
                                 nsCOMPtr<nsIDOMNode> *outNode = 0,
                                 PRInt32 *outOffset = 0);
--- a/editor/libeditor/html/nsHTMLInlineTableEditor.cpp
+++ b/editor/libeditor/html/nsHTMLInlineTableEditor.cpp
@@ -38,16 +38,17 @@
 #include "nsHTMLEditor.h"
 #include "nsIDOMHTMLElement.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIPresShell.h"
 #include "nsIDocumentObserver.h"
 #include "nsIContent.h"
 #include "nsHTMLEditUtils.h"
 #include "nsReadableUtils.h"
+#include "mozilla/dom/Element.h"
 
 // Uncomment the following line if you want to disable
 // table deletion when the only column/row is removed
 // #define DISABLE_TABLE_DELETION 1
 
 NS_IMETHODIMP
 nsHTMLEditor::SetInlineTableEditingEnabled(bool aIsEnabled)
 {
@@ -72,17 +73,17 @@ nsHTMLEditor::ShowInlineTableEditingUI(n
     return NS_OK;
 
   if (mInlineEditedCell) {
     NS_ERROR("call HideInlineTableEditingUI first");
     return NS_ERROR_UNEXPECTED;
   }
 
   // the resizers and the shadow will be anonymous children of the body
-  nsIDOMElement *bodyElement = GetRoot();
+  nsCOMPtr<nsIDOMElement> bodyElement = do_QueryInterface(GetRoot());
   NS_ENSURE_TRUE(bodyElement, NS_ERROR_NULL_POINTER);
 
   CreateAnonymousElement(NS_LITERAL_STRING("a"), bodyElement,
                          NS_LITERAL_STRING("mozTableAddColumnBefore"),
                          false, getter_AddRefs(mAddColumnBeforeButton));
   CreateAnonymousElement(NS_LITERAL_STRING("a"), bodyElement,
                          NS_LITERAL_STRING("mozTableRemoveColumn"),
                          false, getter_AddRefs(mRemoveColumnButton));
@@ -125,20 +126,17 @@ nsHTMLEditor::HideInlineTableEditingUI()
 
   // get the presshell's document observer interface.
   nsCOMPtr<nsIPresShell> ps = GetPresShell();
   // We allow the pres shell to be null; when it is, we presume there
   // are no document observers to notify, but we still want to
   // UnbindFromTree.
 
   // get the root content node.
-
-  nsIDOMElement *bodyElement = GetRoot();
-
-  nsCOMPtr<nsIContent> bodyContent( do_QueryInterface(bodyElement) );
+  nsCOMPtr<nsIContent> bodyContent = GetRoot();
   NS_ENSURE_TRUE(bodyContent, NS_ERROR_FAILURE);
 
   DeleteRefToAnonymousNode(mAddColumnBeforeButton, bodyContent, ps);
   mAddColumnBeforeButton = nsnull;
   DeleteRefToAnonymousNode(mRemoveColumnButton, bodyContent, ps);
   mRemoveColumnButton = nsnull;
   DeleteRefToAnonymousNode(mAddColumnAfterButton, bodyContent, ps);
   mAddColumnAfterButton = nsnull;
--- a/editor/libeditor/text/nsPlaintextEditor.cpp
+++ b/editor/libeditor/text/nsPlaintextEditor.cpp
@@ -70,16 +70,17 @@
 #include "nsEditorUtils.h"  // nsAutoEditBatch, nsAutoRules
 #include "nsUnicharUtils.h"
 #include "nsContentCID.h"
 #include "nsInternetCiter.h"
 #include "nsEventDispatcher.h"
 #include "nsGkAtoms.h"
 #include "nsDebug.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/dom/Element.h"
 
 // Drag & Drop, Clipboard
 #include "nsIClipboard.h"
 #include "nsITransferable.h"
 #include "nsCopySupport.h"
 
 #include "mozilla/FunctionTimer.h"
 
@@ -566,32 +567,32 @@ nsPlaintextEditor::GetTextSelectionOffse
   nsresult rv;
   nsCOMPtr<nsIDOMNode> startNode, endNode;
   PRInt32 startNodeOffset, endNodeOffset;
   aSelection->GetAnchorNode(getter_AddRefs(startNode));
   aSelection->GetAnchorOffset(&startNodeOffset);
   aSelection->GetFocusNode(getter_AddRefs(endNode));
   aSelection->GetFocusOffset(&endNodeOffset);
 
-  nsIDOMElement* rootNode = GetRoot();
+  dom::Element *rootElement = GetRoot();
+  nsCOMPtr<nsIDOMNode> rootNode = do_QueryInterface(rootElement);
   NS_ENSURE_TRUE(rootNode, NS_ERROR_NULL_POINTER);
 
   PRInt32 startOffset = -1;
   PRInt32 endOffset = -1;
 
   nsCOMPtr<nsIContentIterator> iter =
     do_CreateInstance("@mozilla.org/content/post-content-iterator;1", &rv);
   NS_ENSURE_SUCCESS(rv, rv);
     
 #ifdef NS_DEBUG
   PRInt32 nodeCount = 0; // only needed for the assertions below
 #endif
   PRUint32 totalLength = 0;
-  nsCOMPtr<nsIContent> rootContent = do_QueryInterface(rootNode);
-  iter->Init(rootContent);
+  iter->Init(rootElement);
   for (; !iter->IsDone() && (startOffset == -1 || endOffset == -1); iter->Next()) {
     nsCOMPtr<nsIDOMNode> currentNode = do_QueryInterface(iter->GetCurrentNode());
     nsCOMPtr<nsIDOMCharacterData> textNode = do_QueryInterface(currentNode);
     if (textNode) {
       // Note that sometimes we have an empty #text-node as start/endNode,
       // which we regard as not editable because the frame width == 0,
       // see nsEditor::IsEditable().
       bool editable = IsEditable(currentNode);
@@ -1015,26 +1016,25 @@ nsPlaintextEditor::GetTextLength(PRInt32
   
   // special-case for empty document, to account for the bogus node
   bool docEmpty;
   nsresult rv = GetDocumentIsEmpty(&docEmpty);
   NS_ENSURE_SUCCESS(rv, rv);
   if (docEmpty)
     return NS_OK;
 
-  nsIDOMElement* rootNode = GetRoot();
-  NS_ENSURE_TRUE(rootNode, NS_ERROR_NULL_POINTER);
+  dom::Element *rootElement = GetRoot();
+  NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER);
 
   nsCOMPtr<nsIContentIterator> iter =
     do_CreateInstance("@mozilla.org/content/post-content-iterator;1", &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRUint32 totalLength = 0;
-  nsCOMPtr<nsIContent> rootContent = do_QueryInterface(rootNode);
-  iter->Init(rootContent);
+  iter->Init(rootElement);
   for (; !iter->IsDone(); iter->Next()) {
     nsCOMPtr<nsIDOMNode> currentNode = do_QueryInterface(iter->GetCurrentNode());
     nsCOMPtr<nsIDOMCharacterData> textNode = do_QueryInterface(currentNode);
     if (textNode && IsEditable(currentNode)) {
       PRUint32 length;
       textNode->GetLength(&length);
       totalLength += length;
     }
@@ -1099,23 +1099,22 @@ nsPlaintextEditor::SetWrapWidth(PRInt32 
 
   // Make sure we're a plaintext editor, otherwise we shouldn't
   // do the rest of this.
   if (!IsPlaintextEditor())
     return NS_OK;
 
   // Ought to set a style sheet here ...
   // Probably should keep around an mPlaintextStyleSheet for this purpose.
-  nsIDOMElement *rootElement = GetRoot();
+  dom::Element *rootElement = GetRoot();
   NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER);
 
   // Get the current style for this root element:
-  NS_NAMED_LITERAL_STRING(styleName, "style");
   nsAutoString styleValue;
-  nsresult res = rootElement->GetAttribute(styleName, styleValue);
+  nsresult res = rootElement->GetAttr(kNameSpaceID_None, nsGkAtoms::style, styleValue);
   NS_ENSURE_SUCCESS(res, res);
 
   // We'll replace styles for these values:
   CutStyle("white-space", styleValue);
   CutStyle("width", styleValue);
   CutStyle("font-family", styleValue);
 
   // If we have other style left, trim off any existing semicolons
@@ -1149,17 +1148,17 @@ nsPlaintextEditor::SetWrapWidth(PRInt32 
     styleValue.AppendInt(aWrapColumn);
     styleValue.AppendLiteral("ch;");
   }
   else if (mWrapToWindow || aWrapColumn == 0)
     styleValue.AppendLiteral("white-space: pre-wrap;");
   else
     styleValue.AppendLiteral("white-space: pre;");
 
-  return rootElement->SetAttribute(styleName, styleValue);
+  return rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::style, styleValue, true);
 }
 
 NS_IMETHODIMP 
 nsPlaintextEditor::SetWrapColumn(PRInt32 aWrapColumn)
 {
   mWrapColumn = aWrapColumn;
   return NS_OK;
 }
@@ -1349,17 +1348,17 @@ nsPlaintextEditor::GetAndInitDocEncoder(
     if (NS_SUCCEEDED(rv) && selection)
       rv = docEncoder->SetSelection(selection);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   // ... or if the root element is not a body,
   // in which case we set the selection to encompass the root.
   else
   {
-    nsIDOMElement *rootElement = GetRoot();
+    nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
     NS_ENSURE_TRUE(rootElement, NS_ERROR_FAILURE);
     if (!nsTextEditUtils::IsBody(rootElement))
     {
       rv = docEncoder->SetContainerNode(rootElement);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
@@ -1679,17 +1678,17 @@ nsPlaintextEditor::SelectEntireDocument(
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> kungFuDeathGrip(mRules);
 
   // is doc empty?
   bool bDocIsEmpty;
   if (NS_SUCCEEDED(mRules->DocumentIsEmpty(&bDocIsEmpty)) && bDocIsEmpty)
   {
     // get root node
-    nsIDOMElement *rootElement = GetRoot();
+    nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
     NS_ENSURE_TRUE(rootElement, NS_ERROR_FAILURE);
 
     // if it's empty don't select entire doc - that would select the bogus node
     return aSelection->Collapse(rootElement, 0);
   }
 
   nsresult rv = nsEditor::SelectEntireDocument(aSelection);
   NS_ENSURE_SUCCESS(rv, rv);
--- a/editor/libeditor/text/nsTextEditRules.cpp
+++ b/editor/libeditor/text/nsTextEditRules.cpp
@@ -63,16 +63,17 @@
 #include "nsNodeIterator.h"
 #include "nsIDOMNodeFilter.h"
 
 // for IBMBIDI
 #include "nsFrameSelection.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/LookAndFeel.h"
+#include "mozilla/dom/Element.h"
 
 using namespace mozilla;
 
 #define CANCEL_OPERATION_IF_READONLY_OR_DISABLED \
   if (IsReadonly() || IsDisabled()) \
   {                     \
     *aCancel = true; \
     return NS_OK;       \
@@ -455,18 +456,17 @@ nsTextEditRules::CollapseSelectionToTrai
     return NS_OK;
 
   nsCOMPtr<nsIDOMNode> parentNode;
   PRInt32 parentOffset;
   res = nsEditor::GetNodeLocation(selNode, address_of(parentNode),
                                   &parentOffset);
   NS_ENSURE_SUCCESS(res, res);
 
-  nsIDOMElement *rootElem = mEditor->GetRoot();
-  nsCOMPtr<nsIDOMNode> root = do_QueryInterface(rootElem);
+  nsCOMPtr<nsIDOMNode> root = do_QueryInterface(mEditor->GetRoot());
   NS_ENSURE_TRUE(root, NS_ERROR_NULL_POINTER);
   if (parentNode != root) return NS_OK;
 
   nsCOMPtr<nsIDOMNode> nextNode = mEditor->GetChildAt(parentNode,
                                                       parentOffset + 1);
   if (nextNode && nsTextEditUtils::IsMozBR(nextNode))
   {
     res = aSelection->Collapse(parentNode, parentOffset + 1);
@@ -944,17 +944,17 @@ nsTextEditRules::DidUndo(nsISelection *a
   if (!aSelection) { return NS_ERROR_NULL_POINTER; }
   if (NS_SUCCEEDED(res)) 
   {
     if (mBogusNode) {
       mBogusNode = nsnull;
     }
     else
     {
-      nsIDOMElement *theRoot = mEditor->GetRoot();
+      nsCOMPtr<nsIDOMElement> theRoot = do_QueryInterface(mEditor->GetRoot());
       NS_ENSURE_TRUE(theRoot, NS_ERROR_FAILURE);
       nsCOMPtr<nsIDOMNode> node = mEditor->GetLeftmostChild(theRoot);
       if (node && mEditor->IsMozEditorBogusNode(node))
         mBogusNode = node;
     }
   }
   return res;
 }
@@ -977,17 +977,17 @@ nsTextEditRules::DidRedo(nsISelection *a
   if (!aSelection) { return NS_ERROR_NULL_POINTER; }
   if (NS_SUCCEEDED(res)) 
   {
     if (mBogusNode) {
       mBogusNode = nsnull;
     }
     else
     {
-      nsIDOMElement *theRoot = mEditor->GetRoot();
+      nsCOMPtr<nsIDOMElement> theRoot = do_QueryInterface(mEditor->GetRoot());
       NS_ENSURE_TRUE(theRoot, NS_ERROR_FAILURE);
       
       nsCOMPtr<nsIDOMNodeList> nodeList;
       res = theRoot->GetElementsByTagName(NS_LITERAL_STRING("br"),
                                           getter_AddRefs(nodeList));
       NS_ENSURE_SUCCESS(res, res);
       if (nodeList)
       {
@@ -1051,17 +1051,17 @@ nsTextEditRules::RemoveRedundantTrailing
   // If the bogus node exists, we have no work to do
   if (mBogusNode)
     return NS_OK;
 
   // Likewise, nothing to be done if we could never have inserted a trailing br
   if (IsSingleLineEditor())
     return NS_OK;
 
-  nsIDOMNode* body = mEditor->GetRoot();
+  nsCOMPtr<nsIDOMNode> body = do_QueryInterface(mEditor->GetRoot());
   if (!body)
     return NS_ERROR_NULL_POINTER;
 
   bool hasChildren;
   nsresult res = body->HasChildNodes(&hasChildren);
   NS_ENSURE_SUCCESS(res, res);
 
   if (hasChildren) {
@@ -1106,17 +1106,17 @@ nsTextEditRules::RemoveRedundantTrailing
 }
 
 nsresult
 nsTextEditRules::CreateTrailingBRIfNeeded()
 {
   // but only if we aren't a single line edit field
   if (IsSingleLineEditor())
     return NS_OK;
-  nsIDOMNode *body = mEditor->GetRoot();
+  nsCOMPtr<nsIDOMNode> body = do_QueryInterface(mEditor->GetRoot());
   NS_ENSURE_TRUE(body, NS_ERROR_NULL_POINTER);
   nsCOMPtr<nsIDOMNode> lastChild;
   nsresult res = body->GetLastChild(getter_AddRefs(lastChild));
   // assuming CreateBogusNodeIfNeeded() has been called first
   NS_ENSURE_SUCCESS(res, res);  
   NS_ENSURE_TRUE(lastChild, NS_ERROR_NULL_POINTER);
 
   if (!nsTextEditUtils::IsBreak(lastChild))
@@ -1136,17 +1136,17 @@ nsTextEditRules::CreateBogusNodeIfNeeded
 {
   if (!aSelection) { return NS_ERROR_NULL_POINTER; }
   if (!mEditor) { return NS_ERROR_NULL_POINTER; }
   if (mBogusNode) return NS_OK;  // let's not create more than one, ok?
 
   // tell rules system to not do any post-processing
   nsAutoRules beginRulesSniffing(mEditor, nsEditor::kOpIgnore, nsIEditor::eNone);
 
-  nsIDOMNode* body = mEditor->GetRoot();
+  nsCOMPtr<nsIDOMNode> body = do_QueryInterface(mEditor->GetRoot());
   if (!body)
   {
     // we don't even have a body yet, don't insert any bogus nodes at
     // this point.
 
     return NS_OK;
   }
 
--- a/gfx/src/nsScriptableRegion.cpp
+++ b/gfx/src/nsScriptableRegion.cpp
@@ -157,16 +157,20 @@ NS_IMETHODIMP nsScriptableRegion::GetRec
   PRUint32 numRects = mRegion.GetNumRects();
 
   if (!numRects) {
     *aRects = JSVAL_NULL;
     return NS_OK;
   }
 
   JSObject* destArray = JS_NewArrayObject(aCx, numRects * 4, NULL);
+  if (!destArray) {
+    return NS_ERROR_OUT_OF_MEMORY;
+  }
+
   *aRects = OBJECT_TO_JSVAL(destArray);
 
   uint32 n = 0;
   nsIntRegionRectIterator iter(mRegion);
   const nsIntRect *rect;
 
   while ((rect = iter.Next())) {
     // This will contain bogus data if values don't fit in 31 bit
--- a/js/xpconnect/idl/xpccomponents.idl
+++ b/js/xpconnect/idl/xpccomponents.idl
@@ -148,17 +148,17 @@ interface nsIXPCComponents_utils_Sandbox
 interface ScheduledGCCallback : nsISupports
 {
     void callback();
 };
 
 /**
 * interface of Components.utils
 */
-[scriptable, uuid(d6916b9e-0947-400f-8552-81fd96312c9d)]
+[scriptable, uuid(1fbd5d17-707f-4874-9635-59ad2438caf0)]
 interface nsIXPCComponents_Utils : nsISupports
 {
 
     /* reportError is designed to be called from JavaScript only.
      *
      * It will report a JS Error object to the JS console, and return. It
      * is meant for use in exception handler blocks which want to "eat"
      * an exception, but still want to report it to the console.
@@ -283,17 +283,18 @@ interface nsIXPCComponents_Utils : nsISu
     /*
      * To be called from JS only.
      *
      * Returns the global object with which the given object is associated.
      *
      * @param obj The JavaScript object whose global is to be gotten.
      * @return the corresponding global.
      */
-    void /* JSObject */ getGlobalForObject(/* in JSObject obj */);
+    [implicit_jscontext]
+    jsval getGlobalForObject(in jsval obj);
 
     /*
      * To be called from JS only.
      *
      * Returns an object created in |vobj|'s compartment.
      */
     [implicit_jscontext]
     jsval createObjectIn(in jsval vobj);
--- a/js/xpconnect/idl/xpcjsid.idl
+++ b/js/xpconnect/idl/xpcjsid.idl
@@ -1,11 +1,10 @@
-/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- *
- * ***** BEGIN LICENSE BLOCK *****
+/* -*- Mode: IDL; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** 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,
@@ -60,21 +59,21 @@ interface nsIJSID : nsISupports
     [notxpcom] const_nsID_ptr getID();
 };
 
 [scriptable, uuid(e76ec564-a080-4705-8609-384c755ec91e)]
 interface nsIJSIID : nsIJSID
 {
 };
 
-[scriptable, uuid(26b2a374-6eaf-46d4-acaf-1c6be152d36b)]
+[scriptable, uuid(bf5eb086-9eaa-4694-aec3-fe4aac6119bd)]
 interface nsIJSCID : nsIJSID
 {
-    nsISupports createInstance();
-    nsISupports getService();
+    [implicit_jscontext,optional_argc] jsval createInstance([optional] in jsval iid);
+    [implicit_jscontext,optional_argc] jsval getService([optional] in jsval iid);
 };
 
 /* this goes into the C++ header verbatim. */
 %{ C++
 /********************************************************/
 // {F24A14F0-4FA1-11d3-9894-006008962422}
 #define NS_JS_ID_CID  \
 { 0xf24a14f0, 0x4fa1, 0x11d3, \
--- a/js/xpconnect/src/XPCComponents.cpp
+++ b/js/xpconnect/src/XPCComponents.cpp
@@ -3808,67 +3808,31 @@ nsXPCComponents_Utils::NondeterministicG
     if(!JS_NondeterministicGetWeakMapKeys(aCx, JSVAL_TO_OBJECT(aMap), &objRet))
         return NS_ERROR_OUT_OF_MEMORY;
     *aKeys = objRet ? OBJECT_TO_JSVAL(objRet) : JSVAL_VOID;
     return NS_OK;
 }
 
 /* void getGlobalForObject(); */
 NS_IMETHODIMP
-nsXPCComponents_Utils::GetGlobalForObject()
+nsXPCComponents_Utils::GetGlobalForObject(const JS::Value& object,
+                                          JSContext *cx,
+                                          JS::Value *retval)
 {
-  nsresult rv;
-  nsCOMPtr<nsIXPConnect> xpc(do_GetService(nsIXPConnect::GetCID(), &rv));
-  if (NS_FAILED(rv))
-    return NS_ERROR_FAILURE;
-
-  // get the xpconnect native call context
-  nsAXPCNativeCallContext *cc = nsnull;
-  xpc->GetCurrentNativeCallContext(&cc);
-  if (!cc)
-    return NS_ERROR_FAILURE;
-
-  // Get JSContext of current call
-  JSContext* cx;
-  rv = cc->GetJSContext(&cx);
-  if (NS_FAILED(rv) || !cx)
-    return NS_ERROR_FAILURE;
-
-  // get place for return value
-  jsval *rval = nsnull;
-  rv = cc->GetRetValPtr(&rval);
-  if (NS_FAILED(rv) || !rval)
-    return NS_ERROR_FAILURE;
-
-  // get argc and argv and verify arg count
-  PRUint32 argc;
-  rv = cc->GetArgc(&argc);
-  if (NS_FAILED(rv))
-    return NS_ERROR_FAILURE;
-
-  if (argc != 1)
-    return NS_ERROR_XPC_NOT_ENOUGH_ARGS;
-
-  jsval* argv;
-  rv = cc->GetArgvPtr(&argv);
-  if (NS_FAILED(rv) || !argv)
-    return NS_ERROR_FAILURE;
-
-  // first argument must be an object
-  if (JSVAL_IS_PRIMITIVE(argv[0]))
+  // First argument must be an object.
+  if (JSVAL_IS_PRIMITIVE(object))
     return NS_ERROR_XPC_BAD_CONVERT_JS;
 
-  JSObject *obj = JS_GetGlobalForObject(cx, JSVAL_TO_OBJECT(argv[0]));
-  *rval = OBJECT_TO_JSVAL(obj);
+  JSObject *obj = JS_GetGlobalForObject(cx, JSVAL_TO_OBJECT(object));
+  *retval = OBJECT_TO_JSVAL(obj);
 
   // Outerize if necessary.
   if (JSObjectOp outerize = js::GetObjectClass(obj)->ext.outerObject)
-      *rval = OBJECT_TO_JSVAL(outerize(cx, obj));
-
-  cc->SetReturnValueWasSet(true);
+      *retval = OBJECT_TO_JSVAL(outerize(cx, obj));
+
   return NS_OK;
 }
 
 /* jsval createObjectIn(in jsval vobj); */
 NS_IMETHODIMP
 nsXPCComponents_Utils::CreateObjectIn(const jsval &vobj, JSContext *cx, jsval *rval)
 {
     if (!cx)
--- a/js/xpconnect/src/XPCJSID.cpp
+++ b/js/xpconnect/src/XPCJSID.cpp
@@ -674,168 +674,146 @@ nsJSCID::NewID(const char* str)
         }
         if (!success)
             NS_RELEASE(idObj);
     }
     return idObj;
 }
 
 static const nsID*
-GetIIDArg(PRUint32 argc, jsval* argv, JSContext* cx)
+GetIIDArg(PRUint32 argc, const JS::Value& val, JSContext* cx)
 {
     const nsID* iid;
 
     // If an IID was passed in then use it
     if (argc) {
         JSObject* iidobj;
-        jsval val = *argv;
         if (JSVAL_IS_PRIMITIVE(val) ||
             !(iidobj = JSVAL_TO_OBJECT(val)) ||
             !(iid = xpc_JSObjectToID(cx, iidobj))) {
             return nsnull;
         }
     } else
         iid = &NS_GET_IID(nsISupports);
 
     return iid;
 }
 
+static JSObject*
+GetWrapperObject()
+{
+    nsXPConnect* xpc = nsXPConnect::GetXPConnect();
+    if (!xpc)
+        return NULL;
+
+    nsAXPCNativeCallContext *ccxp = NULL;
+    xpc->GetCurrentNativeCallContext(&ccxp);
+    if (!ccxp)
+        return NULL;
+
+    nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
+    ccxp->GetCalleeWrapper(getter_AddRefs(wrapper));
+    JSObject* obj;
+    wrapper->GetJSObject(&obj);
+    return obj;
+}
+
 /* nsISupports createInstance (); */
 NS_IMETHODIMP
-nsJSCID::CreateInstance(nsISupports **_retval)
+nsJSCID::CreateInstance(const JS::Value& iidval, JSContext* cx,
+                        PRUint8 optionalArgc, JS::Value* retval)
 {
     if (!mDetails.IsValid())
         return NS_ERROR_XPC_BAD_CID;
 
-    nsXPConnect* xpc = nsXPConnect::GetXPConnect();
-    if (!xpc)
-        return NS_ERROR_UNEXPECTED;
-
-    nsAXPCNativeCallContext *ccxp = nsnull;
-    xpc->GetCurrentNativeCallContext(&ccxp);
-    if (!ccxp)
+    JSObject* obj = GetWrapperObject();
+    if (!obj) {
         return NS_ERROR_UNEXPECTED;
-
-    PRUint32 argc;
-    jsval * argv;
-    jsval * vp;
-    JSContext* cx;
-    JSObject* obj;
-
-    ccxp->GetJSContext(&cx);
-    ccxp->GetArgc(&argc);
-    ccxp->GetArgvPtr(&argv);
-    ccxp->GetRetValPtr(&vp);
-
-    nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
-    ccxp->GetCalleeWrapper(getter_AddRefs(wrapper));
-    wrapper->GetJSObject(&obj);
+    }
 
     // Do the security check if necessary
-
     XPCContext* xpcc = XPCContext::GetXPCContext(cx);
 
     nsIXPCSecurityManager* sm;
     sm = xpcc->GetAppropriateSecurityManager(nsIXPCSecurityManager::HOOK_CREATE_INSTANCE);
     if (sm && NS_FAILED(sm->CanCreateInstance(cx, mDetails.ID()))) {
         NS_ERROR("how are we not being called from chrome here?");
         return NS_OK;
     }
 
     // If an IID was passed in then use it
-    const nsID* iid = GetIIDArg(argc, argv, cx);
+    const nsID* iid = GetIIDArg(optionalArgc, iidval, cx);
     if (!iid)
         return NS_ERROR_XPC_BAD_IID;
 
     nsCOMPtr<nsIComponentManager> compMgr;
     nsresult rv = NS_GetComponentManager(getter_AddRefs(compMgr));
     if (NS_FAILED(rv))
         return NS_ERROR_UNEXPECTED;
 
     nsCOMPtr<nsISupports> inst;
     rv = compMgr->CreateInstance(mDetails.ID(), nsnull, *iid, getter_AddRefs(inst));
     NS_ASSERTION(NS_FAILED(rv) || inst, "component manager returned success, but instance is null!");
 
     if (NS_FAILED(rv) || !inst)
         return NS_ERROR_XPC_CI_RETURNED_FAILURE;
 
-    rv = xpc->WrapNativeToJSVal(cx, obj, inst, nsnull, iid, true, vp, nsnull);
-    if (NS_FAILED(rv) || JSVAL_IS_PRIMITIVE(*vp))
+    rv = nsXPConnect::GetXPConnect()->WrapNativeToJSVal(cx, obj, inst, nsnull, iid, true, retval, nsnull);
+    if (NS_FAILED(rv) || JSVAL_IS_PRIMITIVE(*retval))
         return NS_ERROR_XPC_CANT_CREATE_WN;
-    ccxp->SetReturnValueWasSet(true);
     return NS_OK;
 }
 
 /* nsISupports getService (); */
 NS_IMETHODIMP
-nsJSCID::GetService(nsISupports **_retval)
+nsJSCID::GetService(const JS::Value& iidval, JSContext* cx,
+                    PRUint8 optionalArgc, JS::Value* retval)
 {
     if (!mDetails.IsValid())
         return NS_ERROR_XPC_BAD_CID;
 
-    nsXPConnect* xpc = nsXPConnect::GetXPConnect();
-    if (!xpc)
-        return NS_ERROR_UNEXPECTED;
-
-    nsAXPCNativeCallContext *ccxp = nsnull;
-    xpc->GetCurrentNativeCallContext(&ccxp);
-    if (!ccxp)
+    JSObject* obj = GetWrapperObject();
+    if (!obj) {
         return NS_ERROR_UNEXPECTED;
-
-    PRUint32 argc;
-    jsval * argv;
-    jsval * vp;
-    JSContext* cx;
-    JSObject* obj;
-
-    ccxp->GetJSContext(&cx);
-    ccxp->GetArgc(&argc);
-    ccxp->GetArgvPtr(&argv);
-    ccxp->GetRetValPtr(&vp);
-
-    nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
-    ccxp->GetCalleeWrapper(getter_AddRefs(wrapper));
-    wrapper->GetJSObject(&obj);
+    }
 
     // Do the security check if necessary
-
     XPCContext* xpcc = XPCContext::GetXPCContext(cx);
 
     nsIXPCSecurityManager* sm;
     sm = xpcc->GetAppropriateSecurityManager(nsIXPCSecurityManager::HOOK_GET_SERVICE);
     if (sm && NS_FAILED(sm->CanCreateInstance(cx, mDetails.ID()))) {
         NS_ASSERTION(JS_IsExceptionPending(cx),
                      "security manager vetoed GetService without setting exception");
         return NS_OK;
     }
 
     // If an IID was passed in then use it
-    const nsID* iid = GetIIDArg(argc, argv, cx);
+    const nsID* iid = GetIIDArg(optionalArgc, iidval, cx);
     if (!iid)
         return NS_ERROR_XPC_BAD_IID;
 
     nsCOMPtr<nsIServiceManager> svcMgr;
     nsresult rv = NS_GetServiceManager(getter_AddRefs(svcMgr));
     if (NS_FAILED(rv))
         return rv;
 
     nsCOMPtr<nsISupports> srvc;
     rv = svcMgr->GetService(mDetails.ID(), *iid, getter_AddRefs(srvc));
     NS_ASSERTION(NS_FAILED(rv) || srvc, "service manager returned success, but service is null!");
     if (NS_FAILED(rv) || !srvc)
         return NS_ERROR_XPC_GS_RETURNED_FAILURE;
 
     JSObject* instJSObj;
     nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
-    rv = xpc->WrapNative(cx, obj, srvc, *iid, getter_AddRefs(holder));
+    rv = nsXPConnect::GetXPConnect()->WrapNative(cx, obj, srvc, *iid, getter_AddRefs(holder));
     if (NS_FAILED(rv) || !holder || NS_FAILED(holder->GetJSObject(&instJSObj)))
         return NS_ERROR_XPC_CANT_CREATE_WN;
 
-    *vp = OBJECT_TO_JSVAL(instJSObj);
-    ccxp->SetReturnValueWasSet(true);
+    *retval = OBJECT_TO_JSVAL(instJSObj);
     return NS_OK;
 }
 
 /* bool construct (in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj, in PRUint32 argc, in JSValPtr argv, in JSValPtr vp); */
 NS_IMETHODIMP
 nsJSCID::Construct(nsIXPConnectWrappedNative *wrapper,
                    JSContext * cx, JSObject * obj,
                    PRUint32 argc, jsval * argv, jsval * vp,
--- a/layout/base/nsCSSRendering.cpp
+++ b/layout/base/nsCSSRendering.cpp
@@ -3831,19 +3831,18 @@ ImageRenderer::PrepareImage()
           nsSVGEffects::BackgroundImageProperty());
       if (!property)
         return false;
       mPaintServerFrame = property->GetReferencedFrame();
 
       // If the referenced element doesn't have a frame we might still be able
       // to paint it if it's an <img>, <canvas>, or <video> element.
       if (!mPaintServerFrame) {
-        nsCOMPtr<nsIDOMElement> imageElement =
-          do_QueryInterface(property->GetReferencedElement());
-        mImageElementSurface = nsLayoutUtils::SurfaceFromElement(imageElement);
+        mImageElementSurface =
+          nsLayoutUtils::SurfaceFromElement(property->GetReferencedElement());
         if (!mImageElementSurface.mSurface)
           return false;
       }
       mIsReady = true;
       break;
     }
     case eStyleImageType_Null:
     default:
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -3912,38 +3912,33 @@ nsLayoutUtils::IsReallyFixedPos(nsIFrame
                   "IsReallyFixedPos called on non-'position:fixed' frame");
 
   nsIAtom *parentType = aFrame->GetParent()->GetType();
   return parentType == nsGkAtoms::viewportFrame ||
          parentType == nsGkAtoms::pageContentFrame;
 }
 
 nsLayoutUtils::SurfaceFromElementResult
-nsLayoutUtils::SurfaceFromElement(nsIDOMElement *aElement,
+nsLayoutUtils::SurfaceFromElement(dom::Element* aElement,
                                   PRUint32 aSurfaceFlags)
 {
   SurfaceFromElementResult result;
   nsresult rv;
 
-  nsCOMPtr<nsINode> node = do_QueryInterface(aElement);
-
   bool forceCopy = (aSurfaceFlags & SFE_WANT_NEW_SURFACE) != 0;
   bool wantImageSurface = (aSurfaceFlags & SFE_WANT_IMAGE_SURFACE) != 0;
 
   if (aSurfaceFlags & SFE_NO_PREMULTIPLY_ALPHA) {
     forceCopy = true;
     wantImageSurface = true;
   }
 
   // If it's a <canvas>, we may be able to just grab its internal surface
-  nsCOMPtr<nsIDOMHTMLCanvasElement> domCanvas = do_QueryInterface(aElement);
-  if (node && domCanvas) {
-    nsHTMLCanvasElement *canvas = static_cast<nsHTMLCanvasElement*>(domCanvas.get());
-    nsIntSize nssize = canvas->GetSize();
-    gfxIntSize size(nssize.width, nssize.height);
+  if (nsHTMLCanvasElement* canvas = nsHTMLCanvasElement::FromContent(aElement)) {
+    gfxIntSize size = canvas->GetSize();
 
     nsRefPtr<gfxASurface> surf;
 
     if (!forceCopy && canvas->CountContexts() == 1) {
       nsICanvasRenderingContextInternal *srcCanvas = canvas->GetContextAtIndex(0);
       rv = srcCanvas->GetThebesSurface(getter_AddRefs(surf));
 
       if (NS_FAILED(rv))
@@ -3957,47 +3952,44 @@ nsLayoutUtils::SurfaceFromElement(nsIDOM
       if (wantImageSurface) {
         surf = new gfxImageSurface(size, gfxASurface::ImageFormatARGB32);
       } else {
         surf = gfxPlatform::GetPlatform()->CreateOffscreenSurface(size, gfxASurface::CONTENT_COLOR_ALPHA);
       }
 
       nsRefPtr<gfxContext> ctx = new gfxContext(surf);
       // XXX shouldn't use the external interface, but maybe we can layerify this
-      rv = (static_cast<nsICanvasElementExternal*>(canvas))->RenderContextsExternal(ctx, gfxPattern::FILTER_NEAREST);
+      rv = canvas->RenderContextsExternal(ctx, gfxPattern::FILTER_NEAREST);
       if (NS_FAILED(rv))
         return result;
     }
 
     // Ensure that any future changes to the canvas trigger proper invalidation,
     // in case this is being used by -moz-element()
     canvas->MarkContextClean();
 
     if (aSurfaceFlags & SFE_NO_PREMULTIPLY_ALPHA) {
       // we can modify this surface since we force a copy above when
       // when NO_PREMULTIPLY_ALPHA is set
       gfxUtils::UnpremultiplyImageSurface(static_cast<gfxImageSurface*>(surf.get()));
     }
 
     result.mSurface = surf;
     result.mSize = size;
-    result.mPrincipal = node->NodePrincipal();
+    result.mPrincipal = aElement->NodePrincipal();
     result.mIsWriteOnly = canvas->IsWriteOnly();
 
     return result;
   }
 
 #ifdef MOZ_MEDIA
   // Maybe it's <video>?
-  nsCOMPtr<nsIDOMHTMLVideoElement> ve = do_QueryInterface(aElement);
-  if (node && ve) {
-    nsHTMLVideoElement *video = static_cast<nsHTMLVideoElement*>(ve.get());
-
-    unsigned short readyState;
-    if (NS_SUCCEEDED(ve->GetReadyState(&readyState)) &&
+  if (nsHTMLVideoElement* video = nsHTMLVideoElement::FromContent(aElement)) {
+    PRUint16 readyState;
+    if (NS_SUCCEEDED(video->GetReadyState(&readyState)) &&
         (readyState == nsIDOMHTMLMediaElement::HAVE_NOTHING ||
          readyState == nsIDOMHTMLMediaElement::HAVE_METADATA)) {
       result.mIsStillLoading = true;
       return result;
     }
 
     // If it doesn't have a principal, just bail
     nsCOMPtr<nsIPrincipal> principal = video->GetCurrentPrincipal();
--- a/layout/base/nsLayoutUtils.h
+++ b/layout/base/nsLayoutUtils.h
@@ -68,16 +68,22 @@ class nsFontFaceList;
 #include "nsCSSPseudoElements.h"
 #include "nsHTMLReflowState.h"
 #include "nsIFrameLoader.h"
 #include "Layers.h"
 
 class nsBlockFrame;
 class gfxDrawable;
 
+namespace mozilla {
+namespace dom {
+class Element;
+} // namespace dom
+} // namespace mozilla
+
 /**
  * nsLayoutUtils is a namespace class used for various helper
  * functions that are useful in multiple places in layout.  The goal
  * is not to define multiple copies of the same static helper.
  */
 class nsLayoutUtils
 {
   typedef gfxPattern::GraphicsFilter GraphicsFilter;
@@ -1376,17 +1382,17 @@ public:
     bool mIsWriteOnly;
     /* Whether the element was still loading.  Some consumers need to handle
        this case specially. */
     bool mIsStillLoading;
     /* Whether the element used CORS when loading. */
     bool mCORSUsed;
   };
 
-  static SurfaceFromElementResult SurfaceFromElement(nsIDOMElement *aElement,
+  static SurfaceFromElementResult SurfaceFromElement(mozilla::dom::Element *aElement,
                                                      PRUint32 aSurfaceFlags = 0);
 
   /**
    * When the document is editable by contenteditable attribute of its root
    * content or body content.
    *
    * Be aware, this returns NULL if it's in designMode.
    *