gfx-refcounting
author Benjamin Smedberg <benjamin@smedbergs.us>
Sat, 26 Jul 2008 22:49:39 -0400
changeset 167 a4da40849f5436e629c5732f4368c6c48189637f
parent 154 7b66eb66ba95f04cfa2392550b012262466a1275
permissions -rw-r--r--
State as of now

Bug 421127 - Switch GFX refcounting to its own class hierarchy, so that it doesn't conflict with XPCOMGC work
* * *

diff --git a/chrome/src/Makefile.in b/chrome/src/Makefile.in
--- a/chrome/src/Makefile.in
+++ b/chrome/src/Makefile.in
@@ -59,6 +59,7 @@ REQUIRES	= xpcom \
 		  xuldoc \
 		  gfx \
 		  layout \
+		  thebes \
 		  locale \
 		  necko \
 		  dom \
diff --git a/content/base/src/nsFrameLoader.cpp b/content/base/src/nsFrameLoader.cpp
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -73,6 +73,7 @@
 #include "nsGkAtoms.h"
 #include "nsINameSpaceManager.h"
 
+#include "nsAutoPtr.h"
 #include "nsThreadUtils.h"
 
 class nsAsyncDocShellDestroyer : public nsRunnable
diff --git a/content/canvas/src/nsCanvasRenderingContext2D.cpp b/content/canvas/src/nsCanvasRenderingContext2D.cpp
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -106,6 +106,8 @@
 #include "gfxTextRunCache.h"
 
 #include "nsFrameManager.h"
+
+using namespace mozilla;
 
 #ifndef M_PI
 #define M_PI		3.14159265358979323846
@@ -384,8 +386,8 @@ protected:
     nsCOMPtr<nsICSSParser> mCSSParser;
 
     // yay cairo
-    nsRefPtr<gfxContext> mThebesContext;
-    nsRefPtr<gfxASurface> mThebesSurface;
+    RefPtr<gfxContext> mThebesContext;
+    RefPtr<gfxASurface> mThebesSurface;
 
     PRUint32 mSaveCount;
     cairo_t *mCairo;
@@ -471,7 +473,7 @@ protected:
         float globalAlpha;
 
         nsString font;
-        nsRefPtr<gfxFontGroup> fontGroup;
+        RefPtr<gfxFontGroup> fontGroup;
         TextAlign textAlign;
         TextBaseline textBaseline;
 
@@ -853,7 +855,7 @@ nsCanvasRenderingContext2D::Render(gfxCo
     if (!mThebesSurface)
         return NS_ERROR_FAILURE;
 
-    nsRefPtr<gfxPattern> pat = new gfxPattern(mThebesSurface);
+    RefPtr<gfxPattern> pat = new gfxPattern(mThebesSurface);
 
     gfxContext::GraphicsOperator op = ctx->CurrentOperator();
     if (mOpaque)
@@ -2188,7 +2190,7 @@ nsCanvasRenderingContext2D::MozTextAlong
 nsCanvasRenderingContext2D::MozTextAlongPath(const nsAString& textToDraw, PRBool stroke)
 {
     // Most of this code is copied from its svg equivalent
-    nsRefPtr<gfxFlattenedPath> path(mThebesContext->GetFlattenedPath());
+    RefPtr<gfxFlattenedPath> path(mThebesContext->GetFlattenedPath());
 
     const PRUnichar* textdata;
     textToDraw.GetData(&textdata);
@@ -2745,7 +2747,7 @@ nsCanvasRenderingContext2D::CairoSurface
             rv = canvas->GetSize(&w, &h);
             NS_ENSURE_SUCCESS(rv, rv);
 
-            nsRefPtr<gfxASurface> sourceSurface;
+            RefPtr<gfxASurface> sourceSurface;
 
             if (!forceCopy && canvas->CountContexts() == 1) {
                 nsICanvasRenderingContextInternal *srcCanvas = canvas->GetContextAtIndex(0);
@@ -2755,10 +2757,10 @@ nsCanvasRenderingContext2D::CairoSurface
             }
 
             if (sourceSurface == nsnull) {
-                nsRefPtr<gfxASurface> surf =
+                RefPtr<gfxASurface> surf =
                     gfxPlatform::GetPlatform()->CreateOffscreenSurface
                     (gfxIntSize(w, h), gfxASurface::ImageFormatARGB32);
-                nsRefPtr<gfxContext> ctx = new gfxContext(surf);
+                RefPtr<gfxContext> ctx = new gfxContext(surf);
 
                 // we have to clear first, since some platform surfaces (X11, I'm
                 // looking at you) don't follow the cleared-surface convention.
@@ -2807,13 +2809,13 @@ nsCanvasRenderingContext2D::CairoSurface
     if (heightOut)
         *heightOut = imgHeight;
 
-    nsRefPtr<gfxPattern> gfxpattern;
+    RefPtr<gfxPattern> gfxpattern;
     img->GetPattern(getter_AddRefs(gfxpattern));
-    nsRefPtr<gfxASurface> gfxsurf = gfxpattern->GetSurface();
+    RefPtr<gfxASurface> gfxsurf = gfxpattern->GetSurface();
 
     if (!gfxsurf) {
         gfxsurf = new gfxImageSurface (gfxIntSize(imgWidth, imgHeight), gfxASurface::ImageFormatARGB32);
-        nsRefPtr<gfxContext> ctx = new gfxContext(gfxsurf);
+        RefPtr<gfxContext> ctx = new gfxContext(gfxsurf);
 
         ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
         ctx->SetPattern(gfxpattern);
@@ -3213,9 +3215,7 @@ nsCanvasRenderingContext2D::GetThebesSur
         return NS_ERROR_NOT_AVAILABLE;
     }
 
-    *surface = mThebesSurface.get();
-    NS_ADDREF(*surface);
-
+    *surface = do_AddRef(mThebesSurface).get();
     return NS_OK;
 }
 
diff --git a/content/events/src/nsEventListenerManager.h b/content/events/src/nsEventListenerManager.h
--- a/content/events/src/nsEventListenerManager.h
+++ b/content/events/src/nsEventListenerManager.h
@@ -41,6 +41,7 @@
 #include "nsIEventListenerManager.h"
 #include "jsapi.h"
 #include "nsCOMPtr.h"
+#include "nsAutoPtr.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOM3EventTarget.h"
 #include "nsHashtable.h"
diff --git a/content/svg/content/src/nsSVGFilters.cpp b/content/svg/content/src/nsSVGFilters.cpp
--- a/content/svg/content/src/nsSVGFilters.cpp
+++ b/content/svg/content/src/nsSVGFilters.cpp
@@ -73,6 +73,8 @@
 #undef LoadImage
 #endif
 
+using namespace mozilla;
+
 //--------------------Filter Resource-----------------------
 /**
   * nsSVGFilterResource provides functionality for managing images used by
@@ -171,7 +173,7 @@ private:
 
   nsAutoString mInput, mResult;
   nsRect mSourceRegion, mFilterSubregion, mSurfaceRect;
-  nsRefPtr<gfxImageSurface> mTargetImage;
+  RefPtr<gfxImageSurface> mTargetImage;
   nsSVGFE *mFilter;
   nsSVGFilterInstance* mInstance;
   PRUint8 *mSourceData, *mTargetData;
@@ -227,7 +229,7 @@ nsSVGFilterResource::AcquireSourceImage(
 {
   mInput = aIn->GetAnimValue();
 
-  nsRefPtr<gfxImageSurface> surface;
+  RefPtr<gfxImageSurface> surface;
   mInstance->LookupImage(mInput, getter_AddRefs(surface),
                          &mSourceRegion,
                          mFilter->GetColorModel(mInstance, aIn));
@@ -238,8 +240,7 @@ nsSVGFilterResource::AcquireSourceImage(
   mSourceData = surface->Data();
   *aSourceData = mSourceData;
   if (aSurface) {
-    *aSurface = nsnull;
-    surface.swap(*aSurface);
+    *aSurface = surface.forget().get();
   }
   return NS_OK;
 }
@@ -259,7 +260,7 @@ nsSVGFilterResource::AcquireTargetImage(
   *aTargetData = mTargetData;
   if (aSurface) {
     *aSurface = mTargetImage;
-    NS_ADDREF(*aSurface);
+    mTargetImage->AddReference();
   }
   return NS_OK;
 }
@@ -1576,7 +1577,7 @@ nsSVGFECompositeElement::Filter(nsSVGFil
 {
   nsresult rv;
   PRUint8 *sourceData, *targetData;
-  nsRefPtr<gfxImageSurface> sourceSurface, targetSurface;
+  RefPtr<gfxImageSurface> sourceSurface, targetSurface;
   nsSVGFilterResource fr(this, instance);
 
   rv = fr.AcquireSourceImage(&mStringAttributes[IN2], &sourceData,
@@ -2416,7 +2417,7 @@ nsSVGFEMergeElement::Filter(nsSVGFilterI
 {
   nsresult rv;
   PRUint8 *sourceData, *targetData;
-  nsRefPtr<gfxImageSurface> sourceSurface, targetSurface;
+  RefPtr<gfxImageSurface> sourceSurface, targetSurface;
   nsSVGFilterResource fr(this, instance);
 
   rv = fr.AcquireTargetImage(&targetData, getter_AddRefs(targetSurface));
@@ -2654,7 +2655,7 @@ nsSVGFEOffsetElement::Filter(nsSVGFilter
 {
   nsresult rv;
   PRUint8 *sourceData, *targetData;
-  nsRefPtr<gfxImageSurface> sourceSurface, targetSurface;
+  RefPtr<gfxImageSurface> sourceSurface, targetSurface;
   nsSVGFilterResource fr(this, instance);
 
   rv = fr.AcquireSourceImage(&mStringAttributes[IN1], &sourceData,
@@ -2808,7 +2809,7 @@ nsSVGFEFloodElement::Filter(nsSVGFilterI
 {
   nsresult rv;
   PRUint8 *targetData;
-  nsRefPtr<gfxImageSurface> targetSurface;
+  RefPtr<gfxImageSurface> targetSurface;
   nsSVGFilterResource fr(this, instance);
 
   rv = fr.AcquireTargetImage(&targetData, getter_AddRefs(targetSurface));
@@ -5461,7 +5462,7 @@ nsSVGFEImageElement::Filter(nsSVGFilterI
 {
   nsresult rv;
   PRUint8 *targetData;
-  nsRefPtr<gfxImageSurface> targetSurface;
+  RefPtr<gfxImageSurface> targetSurface;
 
   nsSVGFilterResource fr(this, instance);
 
@@ -5486,7 +5487,7 @@ nsSVGFEImageElement::Filter(nsSVGFilterI
   if (imageContainer)
     imageContainer->GetCurrentFrame(getter_AddRefs(currentFrame));
 
-  nsRefPtr<gfxPattern> thebesPattern = nsnull;
+  RefPtr<gfxPattern> thebesPattern = nsnull;
   if (currentFrame) {
     nsCOMPtr<nsIImage> img(do_GetInterface(currentFrame));
 
diff --git a/content/svg/content/src/nsSVGFilters.h b/content/svg/content/src/nsSVGFilters.h
--- a/content/svg/content/src/nsSVGFilters.h
+++ b/content/svg/content/src/nsSVGFilters.h
@@ -59,10 +59,10 @@ protected:
   nsSVGFE(nsINodeInfo *aNodeInfo) : nsSVGFEBase(aNodeInfo) {}
 
   struct ScaleInfo {
-    nsRefPtr<gfxImageSurface> mRealSource;
-    nsRefPtr<gfxImageSurface> mRealTarget;
-    nsRefPtr<gfxImageSurface> mSource;
-    nsRefPtr<gfxImageSurface> mTarget;
+    mozilla::RefPtr<gfxImageSurface> mRealSource;
+    mozilla::RefPtr<gfxImageSurface> mRealTarget;
+    mozilla::RefPtr<gfxImageSurface> mSource;
+    mozilla::RefPtr<gfxImageSurface> mTarget;
     nsRect mRect; // rect in mSource and mTarget to operate on
     PRPackedBool mRescaling;
   };
diff --git a/content/svg/content/src/nsSVGPathElement.cpp b/content/svg/content/src/nsSVGPathElement.cpp
--- a/content/svg/content/src/nsSVGPathElement.cpp
+++ b/content/svg/content/src/nsSVGPathElement.cpp
@@ -48,6 +48,8 @@
 #include "nsSVGUtils.h"
 #include "nsSVGPoint.h"
 #include "gfxContext.h"
+
+using namespace mozilla;
 
 nsSVGElement::NumberInfo nsSVGPathElement::sNumberInfo = 
                                                   { &nsGkAtoms::pathLength, 0 };
@@ -104,7 +106,7 @@ nsSVGPathElement::GetTotalLength(float *
 {
   *_retval = 0;
 
-  nsRefPtr<gfxFlattenedPath> flat = GetFlattenedPath(nsnull);
+  RefPtr<gfxFlattenedPath> flat = GetFlattenedPath(nsnull);
 
   if (!flat)
     return NS_ERROR_FAILURE;
@@ -120,7 +122,7 @@ nsSVGPathElement::GetPointAtLength(float
 {
   NS_ENSURE_FINITE(distance, NS_ERROR_ILLEGAL_VALUE);
 
-  nsRefPtr<gfxFlattenedPath> flat = GetFlattenedPath(nsnull);
+  RefPtr<gfxFlattenedPath> flat = GetFlattenedPath(nsnull);
   if (!flat)
     return NS_ERROR_FAILURE;
 
@@ -495,7 +497,7 @@ nsSVGPathElement::DidModifySVGObservable
   return nsSVGPathElementBase::DidModifySVGObservable(observable, aModType);
 }
 
-already_AddRefed<gfxFlattenedPath>
+AddRefed<gfxFlattenedPath>
 nsSVGPathElement::GetFlattenedPath(nsIDOMSVGMatrix *aMatrix)
 {
   gfxContext ctx(nsSVGUtils::GetThebesComputationalSurface());
diff --git a/content/svg/content/src/nsSVGPathElement.h b/content/svg/content/src/nsSVGPathElement.h
--- a/content/svg/content/src/nsSVGPathElement.h
+++ b/content/svg/content/src/nsSVGPathElement.h
@@ -104,7 +104,7 @@ public:
   virtual void GetMarkPoints(nsTArray<nsSVGMark> *aMarks);
   virtual void ConstructPath(gfxContext *aCtx);
 
-  virtual already_AddRefed<gfxFlattenedPath> GetFlattenedPath(nsIDOMSVGMatrix *aMatrix);
+  virtual mozilla::AddRefed<gfxFlattenedPath> GetFlattenedPath(nsIDOMSVGMatrix *aMatrix);
 
   // nsIContent interface
   virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
diff --git a/content/svg/content/src/nsSVGPathGeometryElement.cpp b/content/svg/content/src/nsSVGPathGeometryElement.cpp
--- a/content/svg/content/src/nsSVGPathGeometryElement.cpp
+++ b/content/svg/content/src/nsSVGPathGeometryElement.cpp
@@ -36,6 +36,8 @@
 
 #include "nsSVGPathGeometryElement.h"
 
+using namespace mozilla;
+
 nsSVGPathGeometryElement::nsSVGPathGeometryElement(nsINodeInfo *aNodeInfo)
   : nsSVGPathGeometryElementBase(aNodeInfo)
 {
@@ -66,8 +68,8 @@ nsSVGPathGeometryElement::GetMarkPoints(
 {
 }
 
-already_AddRefed<gfxFlattenedPath>
+AddRefed<gfxFlattenedPath>
 nsSVGPathGeometryElement::GetFlattenedPath(nsIDOMSVGMatrix *aMatrix)
 {
-  return nsnull;
+  return AddRefed<gfxFlattenedPath>(nsnull);
 }
diff --git a/content/svg/content/src/nsSVGPathGeometryElement.h b/content/svg/content/src/nsSVGPathGeometryElement.h
--- a/content/svg/content/src/nsSVGPathGeometryElement.h
+++ b/content/svg/content/src/nsSVGPathGeometryElement.h
@@ -61,7 +61,7 @@ public:
   virtual PRBool IsMarkable();
   virtual void GetMarkPoints(nsTArray<nsSVGMark> *aMarks);
   virtual void ConstructPath(gfxContext *aCtx) = 0;
-  virtual already_AddRefed<gfxFlattenedPath> GetFlattenedPath(nsIDOMSVGMatrix *aMatrix);
+  virtual mozilla::AddRefed<gfxFlattenedPath> GetFlattenedPath(nsIDOMSVGMatrix *aMatrix);
 };
 
 #endif
diff --git a/editor/txtsvc/src/Makefile.in b/editor/txtsvc/src/Makefile.in
--- a/editor/txtsvc/src/Makefile.in
+++ b/editor/txtsvc/src/Makefile.in
@@ -57,6 +57,7 @@ REQUIRES	= xpcom \
 		  dom \
 		  widget \
 		  lwbrk \
+		  thebes \
 		  $(NULL)
 
 CPPSRCS		= \
diff --git a/gfx/src/thebes/nsThebesDeviceContext.cpp b/gfx/src/thebes/nsThebesDeviceContext.cpp
--- a/gfx/src/thebes/nsThebesDeviceContext.cpp
+++ b/gfx/src/thebes/nsThebesDeviceContext.cpp
@@ -91,6 +91,8 @@ static nsSystemFontsMac *gSystemFonts = 
 #else
 #error Need to declare gSystemFonts!
 #endif
+
+using namespace mozilla;
 
 #ifdef MOZ_ENABLE_GTK2
 extern "C" {
@@ -309,7 +311,7 @@ nsThebesDeviceContext::CreateRenderingCo
     nsCOMPtr<nsIRenderingContext> pContext;
     rv = CreateRenderingContextInstance(*getter_AddRefs(pContext));
     if (NS_SUCCEEDED(rv)) {
-        nsRefPtr<gfxASurface> surface(aWidget->GetThebesSurface());
+        RefPtr<gfxASurface> surface(aWidget->GetThebesSurface());
         if (surface)
             rv = pContext->Init(this, surface);
         else
diff --git a/gfx/src/thebes/nsThebesDeviceContext.h b/gfx/src/thebes/nsThebesDeviceContext.h
--- a/gfx/src/thebes/nsThebesDeviceContext.h
+++ b/gfx/src/thebes/nsThebesDeviceContext.h
@@ -44,7 +44,7 @@
 
 #include "nsDeviceContext.h"
 
-#include "nsRefPtrHashtable.h"
+#include "nsDataHashtable.h"
 #include "nsHashKeys.h"
 
 #include "prlog.h"
@@ -139,9 +139,10 @@ private:
     nscoord mWidth;
     nscoord mHeight;
 
-    nsRefPtrHashtable<nsISupportsHashKey, gfxASurface> mWidgetSurfaceCache;
+    nsDataHashtable<nsISupportsHashKey,
+                    mozilla::RefPtr<gfxASurface> > mWidgetSurfaceCache;
 
-    nsRefPtr<gfxASurface> mPrintingSurface;
+    mozilla::RefPtr<gfxASurface> mPrintingSurface;
     float mPrintingScale;
     nsCOMPtr<nsIDeviceContextSpec> mDeviceContextSpec;
 };
diff --git a/gfx/src/thebes/nsThebesFontMetrics.h b/gfx/src/thebes/nsThebesFontMetrics.h
--- a/gfx/src/thebes/nsThebesFontMetrics.h
+++ b/gfx/src/thebes/nsThebesFontMetrics.h
@@ -183,7 +183,7 @@ protected:
     };
     friend class AutoTextRun;
 
-    nsRefPtr<gfxFontGroup> mFontGroup;
+    mozilla::RefPtr<gfxFontGroup> mFontGroup;
     gfxFontStyle *mFontStyle;
 
 private:
diff --git a/gfx/src/thebes/nsThebesImage.cpp b/gfx/src/thebes/nsThebesImage.cpp
--- a/gfx/src/thebes/nsThebesImage.cpp
+++ b/gfx/src/thebes/nsThebesImage.cpp
@@ -45,6 +45,8 @@
 #include "gfxPlatform.h"
 
 #include "prenv.h"
+
+using namespace mozilla;
 
 static PRBool gDisableOptimize = PR_FALSE;
 
@@ -309,7 +311,7 @@ nsThebesImage::Optimize(nsIDeviceContext
         if (ddbSize <= kMaxSingleDDBSize &&
             ddbSize + gTotalDDBSize <= kMaxDDBSize)
         {
-            nsRefPtr<gfxWindowsSurface> wsurf = mWinSurface->OptimizeToDDB(nsnull, gfxIntSize(mWidth, mHeight), mFormat);
+            RefPtr<gfxWindowsSurface> wsurf = mWinSurface->OptimizeToDDB(nsnull, gfxIntSize(mWidth, mHeight), mFormat);
             if (wsurf) {
                 gTotalDDBs++;
                 gTotalDDBSize += ddbSize;
@@ -486,7 +488,7 @@ nsThebesImage::Draw(nsIRenderingContext 
     // sample the whole pixel.
     subimageRect.RoundOut();
 
-    nsRefPtr<gfxPattern> pat;
+    RefPtr<gfxPattern> pat;
     PRBool ctxHasNonTranslation = ctx->CurrentMatrix().HasNonTranslation();
     if ((xscale == 1.0 && yscale == 1.0 && !ctxHasNonTranslation) ||
         subimageRect == gfxRect(0, 0, mWidth, mHeight))
@@ -501,7 +503,7 @@ nsThebesImage::Draw(nsIRenderingContext 
         // integer width and height.
         gfxIntSize size(PRInt32(subimageRect.Width()),
                         PRInt32(subimageRect.Height()));
-        nsRefPtr<gfxASurface> temp =
+        RefPtr<gfxASurface> temp =
             gfxPlatform::GetPlatform()->CreateOffscreenSurface(size, mFormat);
         if (!temp || temp->CairoStatus() != 0)
             return NS_ERROR_FAILURE;
@@ -529,7 +531,7 @@ nsThebesImage::Draw(nsIRenderingContext 
         if (dim.width == 0 || dim.height == 0)
             return NS_OK;
 
-        nsRefPtr<gfxASurface> temp =
+        RefPtr<gfxASurface> temp =
             gfxPlatform::GetPlatform()->CreateOffscreenSurface (dim,  mFormat);
         if (!temp || temp->CairoStatus() != 0)
             return NS_ERROR_FAILURE;
@@ -569,7 +571,7 @@ nsThebesImage::Draw(nsIRenderingContext 
 
     pat->SetMatrix(mat);
 
-    nsRefPtr<gfxASurface> target = ctx->CurrentSurface();
+    RefPtr<gfxASurface> target = ctx->CurrentSurface();
     switch (target->GetType()) {
     case gfxASurface::SurfaceTypeXlib:
     case gfxASurface::SurfaceTypeXcb:
@@ -642,7 +644,7 @@ nsThebesImage::ThebesDrawTile(gfxContext
     if (mSinglePixel && !hasPadding) {
         thebesContext->SetDeviceColor(mSinglePixelColor);
     } else {
-        nsRefPtr<gfxASurface> surface;
+        RefPtr<gfxASurface> surface;
         PRInt32 width, height;
 
         if (hasPadding) {
@@ -701,7 +703,7 @@ nsThebesImage::ThebesDrawTile(gfxContext
             // tileWidth, tileHeight), with padX padding added to the left
             // and right sides and padY padding added to the top and bottom
             // sides.
-            nsRefPtr<gfxASurface> tmpSurface;
+            RefPtr<gfxASurface> tmpSurface;
             tmpSurface = gfxPlatform::GetPlatform()->CreateOffscreenSurface(
                     gfxIntSize(tileWidth + 2*padX, tileHeight + 2*padY), format);
             if (!tmpSurface || tmpSurface->CairoStatus()) {
diff --git a/gfx/src/thebes/nsThebesImage.h b/gfx/src/thebes/nsThebesImage.h
--- a/gfx/src/thebes/nsThebesImage.h
+++ b/gfx/src/thebes/nsThebesImage.h
@@ -95,7 +95,7 @@ public:
 
     NS_IMETHOD GetSurface(gfxASurface **aSurface) {
         *aSurface = ThebesSurface();
-        NS_ADDREF(*aSurface);
+        (*aSurface)->AddReference();
         return NS_OK;
     }
 
@@ -104,7 +104,7 @@ public:
             *aPattern = new gfxPattern(mSinglePixelColor);
         else
             *aPattern = new gfxPattern(ThebesSurface());
-        NS_ADDREF(*aPattern);
+        (*aPattern)->AddReference();
         return NS_OK;
     }
 
@@ -169,12 +169,12 @@ protected:
 
     gfxRGBA mSinglePixelColor;
 
-    nsRefPtr<gfxImageSurface> mImageSurface;
-    nsRefPtr<gfxASurface> mOptSurface;
+    mozilla::RefPtr<gfxImageSurface> mImageSurface;
+    mozilla::RefPtr<gfxASurface> mOptSurface;
 #if defined(XP_WIN)
-    nsRefPtr<gfxWindowsSurface> mWinSurface;
+    mozilla::RefPtr<gfxWindowsSurface> mWinSurface;
 #elif defined(XP_MACOSX)
-    nsRefPtr<gfxQuartzImageSurface> mQuartzSurface;
+    mozilla::RefPtr<gfxQuartzImageSurface> mQuartzSurface;
 #endif
 
     PRUint8 mAlphaDepth;
diff --git a/gfx/src/thebes/nsThebesRenderingContext.cpp b/gfx/src/thebes/nsThebesRenderingContext.cpp
--- a/gfx/src/thebes/nsThebesRenderingContext.cpp
+++ b/gfx/src/thebes/nsThebesRenderingContext.cpp
@@ -42,6 +42,7 @@
 
 #include "nsRect.h"
 #include "nsString.h"
+#include "nsAutoPtr.h"
 #include "nsTransform2D.h"
 #include "nsIRegion.h"
 #include "nsIServiceManager.h"
@@ -717,7 +718,7 @@ nsThebesRenderingContext::GetNativeGraph
         return mThebes->GetCairo();
 #ifdef XP_WIN
     if (aType == NATIVE_WINDOWS_DC) {
-        nsRefPtr<gfxASurface> surf(mThebes->CurrentSurface());
+        RefPtr<gfxASurface> surf(mThebes->CurrentSurface());
         if (!surf || surf->CairoStatus())
             return nsnull;
         return static_cast<gfxWindowsSurface*>(static_cast<gfxASurface*>(surf.get()))->GetDC();
diff --git a/gfx/src/thebes/nsThebesRenderingContext.h b/gfx/src/thebes/nsThebesRenderingContext.h
--- a/gfx/src/thebes/nsThebesRenderingContext.h
+++ b/gfx/src/thebes/nsThebesRenderingContext.h
@@ -232,7 +232,7 @@ protected:
     nscolor mColor;
 
     // the rendering context
-    nsRefPtr<gfxContext> mThebes;
+    mozilla::RefPtr<gfxContext> mThebes;
 
     // for handing out to people
     void UpdateTempTransformMatrix();
diff --git a/gfx/thebes/public/gfxASurface.h b/gfx/thebes/public/gfxASurface.h
--- a/gfx/thebes/public/gfxASurface.h
+++ b/gfx/thebes/public/gfxASurface.h
@@ -52,8 +52,9 @@ typedef void (*thebes_destroy_func_t) (v
  */
 class THEBES_API gfxASurface {
 public:
-    nsrefcnt AddRef(void);
-    nsrefcnt Release(void);
+    void AddReference();
+    void ReleaseReference();
+    uint32_t GetRefCount();
 
 public:
     /**
@@ -92,7 +93,7 @@ public:
     } gfxContentType;
 
     /* Wrap the given cairo surface and return a gfxASurface for it */
-    static already_AddRefed<gfxASurface> Wrap(cairo_surface_t *csurf);
+    static mozilla::AddRefed<gfxASurface> Wrap(cairo_surface_t *csurf);
 
     /*** this DOES NOT addref the surface */
     cairo_surface_t *CairoSurface() {
diff --git a/gfx/thebes/public/gfxAlphaRecovery.h b/gfx/thebes/public/gfxAlphaRecovery.h
--- a/gfx/thebes/public/gfxAlphaRecovery.h
+++ b/gfx/thebes/public/gfxAlphaRecovery.h
@@ -47,9 +47,9 @@ public:
      * background and the other on white, return a new surface
      * that contains the contents with recovered alpha.
      */
-    static already_AddRefed<gfxImageSurface> RecoverAlpha (gfxImageSurface *blackSurface,
-                                                           gfxImageSurface *whiteSurface,
-                                                           gfxIntSize dimensions);
+    static mozilla::AddRefed<gfxImageSurface> RecoverAlpha (gfxImageSurface *blackSurface,
+                                                            gfxImageSurface *whiteSurface,
+                                                            gfxIntSize dimensions);
 };
 
 #endif /* _GFXALPHARECOVERY_H_ */
diff --git a/gfx/thebes/public/gfxAtsuiFonts.h b/gfx/thebes/public/gfxAtsuiFonts.h
--- a/gfx/thebes/public/gfxAtsuiFonts.h
+++ b/gfx/thebes/public/gfxAtsuiFonts.h
@@ -92,7 +92,7 @@ protected:
 
     ATSUStyle mATSUStyle;
 
-    nsRefPtr<MacOSFontEntry> mFontEntry;
+    RefPtr<MacOSFontEntry> mFontEntry;
 
     PRBool mValid;
     PRBool mHasMirroring;
@@ -140,7 +140,7 @@ public:
 
     PRBool HasFont(ATSUFontID fid);
 
-    inline gfxAtsuiFont* WhichFontSupportsChar(nsTArray< nsRefPtr<gfxFont> >& aFontList, PRUint32 aCh) {
+    inline gfxAtsuiFont* WhichFontSupportsChar(nsTArray< RefPtr<gfxFont> >& aFontList, PRUint32 aCh) {
         PRUint32 len = aFontList.Length();
         for (PRUint32 i = 0; i < len; i++) {
             gfxAtsuiFont* font = static_cast<gfxAtsuiFont*>(aFontList.ElementAt(i).get());
@@ -151,9 +151,9 @@ public:
     }
 
    // search through pref fonts for a character, return nsnull if no matching pref font
-   already_AddRefed<gfxAtsuiFont> WhichPrefFontSupportsChar(PRUint32 aCh);
+   AddRefed<gfxAtsuiFont> WhichPrefFontSupportsChar(PRUint32 aCh);
    
-   already_AddRefed<gfxAtsuiFont> FindFontForChar(PRUint32 aCh, PRUint32 aPrevCh, PRUint32 aNextCh, gfxAtsuiFont* aPrevMatchedFont);
+   AddRefed<gfxAtsuiFont> FindFontForChar(PRUint32 aCh, PRUint32 aPrevCh, PRUint32 aNextCh, gfxAtsuiFont* aPrevMatchedFont);
 
 protected:
     static PRBool FindATSUFont(const nsAString& aName,
@@ -185,8 +185,8 @@ protected:
                        PRUint32 aOffsetInTextRun, PRUint32 aLengthInTextRun);
     
     // cache the most recent pref font to avoid general pref font lookup
-    nsRefPtr<MacOSFamilyEntry>    mLastPrefFamily;
-    nsRefPtr<gfxAtsuiFont>        mLastPrefFont;
+    RefPtr<MacOSFamilyEntry>   mLastPrefFamily;
+    RefPtr<gfxAtsuiFont>       mLastPrefFont;
     eFontPrefLang                 mLastPrefLang;       // lang group for last pref font
     PRBool                        mLastPrefFirstFont;  // is this the first font in the list of pref fonts for this lang group?
     eFontPrefLang                 mPageLang;
diff --git a/gfx/thebes/public/gfxBeOSPlatform.h b/gfx/thebes/public/gfxBeOSPlatform.h
--- a/gfx/thebes/public/gfxBeOSPlatform.h
+++ b/gfx/thebes/public/gfxBeOSPlatform.h
@@ -52,7 +52,7 @@ public:
         return (gfxBeOSPlatform*) gfxPlatform::GetPlatform();
     }
 
-    already_AddRefed<gfxASurface>
+    AddRefed<gfxASurface>
         CreateOffscreenSurface(PRUint32 width,
                                PRUint32 height,
                                gfxASurface::gfxImageFormat imageFormat);
diff --git a/gfx/thebes/public/gfxContext.h b/gfx/thebes/public/gfxContext.h
--- a/gfx/thebes/public/gfxContext.h
+++ b/gfx/thebes/public/gfxContext.h
@@ -66,7 +66,7 @@ typedef struct _cairo cairo_t;
  * as opposed to app units.
  */
 class THEBES_API gfxContext {
-    THEBES_INLINE_DECL_REFCOUNTING(gfxContext)
+    DECL_INLINE_REFCOUNTING(gfxContext)
 
 public:
     /**
@@ -86,8 +86,8 @@ public:
      * active, returns the surface the gfxContext was created with,
      * and 0,0 in dx,dy.
      */
-    already_AddRefed<gfxASurface> CurrentSurface(gfxFloat *dx, gfxFloat *dy);
-    already_AddRefed<gfxASurface> CurrentSurface() {
+    mozilla::AddRefed<gfxASurface> CurrentSurface(gfxFloat *dx, gfxFloat *dy);
+    mozilla::AddRefed<gfxASurface> CurrentSurface() {
         return CurrentSurface(NULL, NULL);
     }
 
@@ -349,7 +349,7 @@ public:
     /**
      * Get the source pattern (solid color, normal pattern, surface, etc)
      */
-    already_AddRefed<gfxPattern> GetPattern();
+    mozilla::AddRefed<gfxPattern> GetPattern();
 
     /**
      ** Painting
@@ -534,7 +534,7 @@ public:
      * Groups
      */
     void PushGroup(gfxASurface::gfxContentType content = gfxASurface::CONTENT_COLOR);
-    already_AddRefed<gfxPattern> PopGroup();
+    mozilla::AddRefed<gfxPattern> PopGroup();
     void PopGroupToSource();
 
     /**
@@ -553,7 +553,7 @@ public:
     /**
      ** Obtaining a "flattened" path - path converted to all line segments
      **/
-    already_AddRefed<gfxFlattenedPath> GetFlattenedPath();
+    mozilla::AddRefed<gfxFlattenedPath> GetFlattenedPath();
 
     /**
      ** Flags
@@ -585,7 +585,7 @@ public:
 
 private:
     cairo_t *mCairo;
-    nsRefPtr<gfxASurface> mSurface;
+    mozilla::RefPtr<gfxASurface> mSurface;
     PRInt32 mFlags;
 };
 
diff --git a/gfx/thebes/public/gfxFont.h b/gfx/thebes/public/gfxFont.h
--- a/gfx/thebes/public/gfxFont.h
+++ b/gfx/thebes/public/gfxFont.h
@@ -182,8 +182,8 @@ public:
 
     // Look up a font in the cache. Returns an addrefed pointer, or null
     // if there's nothing matching in the cache
-    already_AddRefed<gfxFont> Lookup(const nsAString &aName,
-                                     const gfxFontStyle *aFontGroup);
+    mozilla::AddRefed<gfxFont> Lookup(const nsAString &aName,
+                                       const gfxFontStyle *aFontGroup);
     // We created a new font (presumably because Lookup returned null);
     // put it in the cache. The font's refcount should be nonzero. It is
     // allowable to add a new font even if there is one already in the
@@ -355,32 +355,26 @@ private:
 /* a SPECIFIC single font family */
 class THEBES_API gfxFont {
 public:
-    nsrefcnt AddRef(void) {
-        NS_PRECONDITION(PRInt32(mRefCnt) >= 0, "illegal refcnt");
+    void AddReference(void) {
         if (mExpirationState.IsTracked()) {
             gfxFontCache::GetCache()->RemoveObject(this);
         }
         ++mRefCnt;
-        NS_LOG_ADDREF(this, mRefCnt, "gfxFont", sizeof(*this));
-        return mRefCnt;
     }
-    nsrefcnt Release(void) {
+    void ReleaseReference() {
         NS_PRECONDITION(0 != mRefCnt, "dup release");
         --mRefCnt;
-        NS_LOG_RELEASE(this, mRefCnt, "gfxFont");
         if (mRefCnt == 0) {
             // Don't delete just yet; return the object to the cache for
             // possibly recycling within some time limit
             gfxFontCache::GetCache()->NotifyReleased(this);
-            return 0;
         }
-        return mRefCnt;
     }
 
     PRInt32 GetRefCount() { return mRefCnt; }
 
 protected:
-    nsAutoRefCnt mRefCnt;
+    mozilla::RefCnt mRefCnt;
 
 public:
     gfxFont(const nsAString &aName, const gfxFontStyle *aFontGroup);
@@ -561,7 +555,7 @@ protected:
 };
 
 class THEBES_API gfxTextRunFactory {
-    THEBES_INLINE_DECL_REFCOUNTING(gfxTextRunFactory)
+    DECL_INLINE_REFCOUNTING(gfxTextRunFactory)
 
 public:
     // Flags in the mask 0xFFFF0000 are reserved for textrun clients
@@ -1139,7 +1133,7 @@ public:
 
     // The text is divided into GlyphRuns as necessary
     struct GlyphRun {
-        nsRefPtr<gfxFont> mFont;   // never null
+        mozilla::RefPtr<gfxFont> mFont;   // never null
         PRUint32          mCharacterOffset; // into original UTF16 string
     };
 
@@ -1370,7 +1364,7 @@ private:
         const PRUnichar *mDouble;
     } mText;
     void             *mUserData;
-    gfxFontGroup     *mFontGroup; // addrefed
+    mozilla::RefPtr<gfxFontGroup> mFontGroup;
     gfxSkipChars      mSkipChars;
     nsExpirationState mExpirationState;
     PRUint32          mAppUnitsPerDevUnit;
@@ -1478,7 +1472,7 @@ protected:
 protected:
     nsString mFamilies;
     gfxFontStyle mStyle;
-    nsTArray< nsRefPtr<gfxFont> > mFonts;
+    nsTArray< mozilla::RefPtr<gfxFont> > mFonts;
     gfxFloat mUnderlineOffset;
 
     // Init this font group's font metrics. If there no bad fonts, you don't need to call this.
diff --git a/gfx/thebes/public/gfxOS2Platform.h b/gfx/thebes/public/gfxOS2Platform.h
--- a/gfx/thebes/public/gfxOS2Platform.h
+++ b/gfx/thebes/public/gfxOS2Platform.h
@@ -55,7 +55,7 @@ public:
         return (gfxOS2Platform*) gfxPlatform::GetPlatform();
     }
 
-    already_AddRefed<gfxASurface>
+    AddRefed<gfxASurface>
         CreateOffscreenSurface(const gfxIntSize& size,
                                gfxASurface::gfxImageFormat imageFormat);
 
diff --git a/gfx/thebes/public/gfxPangoFonts.h b/gfx/thebes/public/gfxPangoFonts.h
--- a/gfx/thebes/public/gfxPangoFonts.h
+++ b/gfx/thebes/public/gfxPangoFonts.h
@@ -64,7 +64,7 @@ public:
     gfxPangoFont (const nsAString& aName,
                   const gfxFontStyle *aFontStyle);
     virtual ~gfxPangoFont ();
-    static already_AddRefed<gfxPangoFont> GetOrMakeFont(PangoFont *aPangoFont);
+    static mozilla::AddRefed<gfxPangoFont> GetOrMakeFont(PangoFont *aPangoFont);
 
     static void Shutdown();
 
diff --git a/gfx/thebes/public/gfxPath.h b/gfx/thebes/public/gfxPath.h
--- a/gfx/thebes/public/gfxPath.h
+++ b/gfx/thebes/public/gfxPath.h
@@ -43,7 +43,7 @@ typedef struct cairo_path cairo_path_t;
 typedef struct cairo_path cairo_path_t;
 
 class THEBES_API gfxFlattenedPath {
-    THEBES_INLINE_DECL_REFCOUNTING(gfxPath)
+    DECL_INLINE_REFCOUNTING(gfxPath)
 
 public:
     gfxFlattenedPath(cairo_path_t *aPath);
diff --git a/gfx/thebes/public/gfxPattern.h b/gfx/thebes/public/gfxPattern.h
--- a/gfx/thebes/public/gfxPattern.h
+++ b/gfx/thebes/public/gfxPattern.h
@@ -49,7 +49,7 @@ typedef struct _cairo_pattern cairo_patt
 
 
 class THEBES_API gfxPattern {
-    THEBES_INLINE_DECL_REFCOUNTING(gfxPattern)
+    DECL_INLINE_REFCOUNTING(gfxPattern)
 
 public:
     gfxPattern(cairo_pattern_t *aPattern);
@@ -95,7 +95,7 @@ public:
     /* returns TRUE if it succeeded */
     PRBool GetSolidColor(gfxRGBA& aColor);
 
-    already_AddRefed<gfxASurface> GetSurface();
+    mozilla::AddRefed<gfxASurface> GetSurface();
 
 protected:
     cairo_pattern_t *mPattern;
diff --git a/gfx/thebes/public/gfxPlatform.h b/gfx/thebes/public/gfxPlatform.h
--- a/gfx/thebes/public/gfxPlatform.h
+++ b/gfx/thebes/public/gfxPlatform.h
@@ -135,12 +135,12 @@ public:
      * Create an offscreen surface of the given dimensions
      * and image format.
      */
-    virtual already_AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
-                                                                 gfxASurface::gfxImageFormat imageFormat) = 0;
+    virtual mozilla::AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
+                                                                   gfxASurface::gfxImageFormat imageFormat) = 0;
 
 
-    virtual already_AddRefed<gfxASurface> OptimizeImage(gfxImageSurface *aSurface,
-                                                        gfxASurface::gfxImageFormat format);
+    virtual mozilla::AddRefed<gfxASurface> OptimizeImage(gfxImageSurface *aSurface,
+                                                          gfxASurface::gfxImageFormat format);
 
     /*
      * Font bits
diff --git a/gfx/thebes/public/gfxPlatformGtk.h b/gfx/thebes/public/gfxPlatformGtk.h
--- a/gfx/thebes/public/gfxPlatformGtk.h
+++ b/gfx/thebes/public/gfxPlatformGtk.h
@@ -54,8 +54,8 @@ public:
         return (gfxPlatformGtk*) gfxPlatform::GetPlatform();
     }
 
-    already_AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
-                                                         gfxASurface::gfxImageFormat imageFormat);
+    mozilla::AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
+                                                          gfxASurface::gfxImageFormat imageFormat);
 
     nsresult GetFontList(const nsACString& aLangGroup,
                          const nsACString& aGenericFamily,
diff --git a/gfx/thebes/public/gfxPlatformMac.h b/gfx/thebes/public/gfxPlatformMac.h
--- a/gfx/thebes/public/gfxPlatformMac.h
+++ b/gfx/thebes/public/gfxPlatformMac.h
@@ -53,11 +53,11 @@ public:
         return (gfxPlatformMac*) gfxPlatform::GetPlatform();
     }
 
-    already_AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
-                                                         gfxASurface::gfxImageFormat imageFormat);
+    AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
+                                                           gfxASurface::gfxImageFormat imageFormat);
 
-    already_AddRefed<gfxASurface> OptimizeImage(gfxImageSurface *aSurface,
-                                                gfxASurface::gfxImageFormat format);
+    AddRefed<gfxASurface> OptimizeImage(gfxImageSurface *aSurface,
+                                        gfxASurface::gfxImageFormat format);
 
     nsresult ResolveFontName(const nsAString& aFontName,
                              FontResolverCallback aCallback,
diff --git a/gfx/thebes/public/gfxQuartzImageSurface.h b/gfx/thebes/public/gfxQuartzImageSurface.h
--- a/gfx/thebes/public/gfxQuartzImageSurface.h
+++ b/gfx/thebes/public/gfxQuartzImageSurface.h
@@ -48,7 +48,7 @@ public:
 
     virtual ~gfxQuartzImageSurface();
 
-    already_AddRefed<gfxImageSurface> GetImageSurface();
+    AddRefed<gfxImageSurface> GetImageSurface();
 };
 
 #endif /* GFX_QUARTZIMAGESURFACE_H */
diff --git a/gfx/thebes/public/gfxQuartzNativeDrawing.h b/gfx/thebes/public/gfxQuartzNativeDrawing.h
--- a/gfx/thebes/public/gfxQuartzNativeDrawing.h
+++ b/gfx/thebes/public/gfxQuartzNativeDrawing.h
@@ -74,11 +74,11 @@ private:
     gfxQuartzNativeDrawing(const gfxQuartzNativeDrawing&);
     const gfxQuartzNativeDrawing& operator=(const gfxQuartzNativeDrawing&);
 
-    nsRefPtr<gfxContext> mContext;
+    RefPtr<gfxContext> mContext;
     gfxRect mNativeRect; // not yet used, will be needed for offscreen buffers
 
     // saved state
-    nsRefPtr<gfxQuartzSurface> mQuartzSurface;
+    RefPtr<gfxQuartzSurface> mQuartzSurface;
     CGContextRef mCGContext;
 };
 
diff --git a/gfx/thebes/public/gfxTypes.h b/gfx/thebes/public/gfxTypes.h
--- a/gfx/thebes/public/gfxTypes.h
+++ b/gfx/thebes/public/gfxTypes.h
@@ -39,6 +39,10 @@
 #define GFX_TYPES_H
 
 #include "prtypes.h"
+#include "nscore.h"
+#include "nsDebug.h"
+
+#include "mozilla/RefPtr.h"
 
 /**
  * Currently needs to be 'double' for Cairo compatibility. Could
@@ -54,34 +58,4 @@ typedef double gfxFloat;
 # define THEBES_API NS_IMPORT
 #endif
 
-/**
- * Define refcounting for Thebes.  For now use the stuff from nsISupportsImpl
- * even though it forces the functions to be virtual...
- */
-#include "nsISupportsImpl.h"
-#include "nsAutoPtr.h"
-
-#define THEBES_INLINE_DECL_REFCOUNTING(_class)                                \
-public:                                                                       \
-    nsrefcnt AddRef(void) {                                                   \
-        NS_PRECONDITION(PRInt32(mRefCnt) >= 0, "illegal refcnt");             \
-        ++mRefCnt;                                                            \
-        NS_LOG_ADDREF(this, mRefCnt, #_class, sizeof(*this));                 \
-        return mRefCnt;                                                       \
-    }                                                                         \
-    nsrefcnt Release(void) {                                                  \
-        NS_PRECONDITION(0 != mRefCnt, "dup release");                         \
-        --mRefCnt;                                                            \
-        NS_LOG_RELEASE(this, mRefCnt, #_class);                               \
-        if (mRefCnt == 0) {                                                   \
-            mRefCnt = 1; /* stabilize */                                      \
-            NS_DELETEXPCOM(this);                                             \
-            return 0;                                                         \
-        }                                                                     \
-        return mRefCnt;                                                       \
-    }                                                                         \
-protected:                                                                    \
-    nsAutoRefCnt mRefCnt;                                                     \
-public:
-
 #endif /* GFX_TYPES_H */
diff --git a/gfx/thebes/public/gfxWindowsFonts.h b/gfx/thebes/public/gfxWindowsFonts.h
--- a/gfx/thebes/public/gfxWindowsFonts.h
+++ b/gfx/thebes/public/gfxWindowsFonts.h
@@ -319,8 +319,7 @@ private:
 
     LOGFONTW mLogFont;
 
-    nsRefPtr<FontEntry> mFontEntry;
-    PRPackedBool mIsValid;
+    RefPtr<FontEntry> mFontEntry;
     
     virtual PRBool SetupCairoFont(gfxContext *aContext);
 };
@@ -348,7 +347,7 @@ public:
         return mGenericFamily;
     }
 
-    const nsTArray<nsRefPtr<FontEntry> >& GetFontList() const {
+    const nsTArray<RefPtr<FontEntry> >& GetFontList() const {
         return mFontEntries;
     }
     PRUint32 FontListLength() const {
@@ -375,7 +374,7 @@ private:
 private:
 
     nsCString mGenericFamily;
-    nsTArray<nsRefPtr<FontEntry> > mFontEntries;
+    nsTArray<RefPtr<FontEntry> > mFontEntries;
 };
 
 #endif /* GFX_WINDOWSFONTS_H */
diff --git a/gfx/thebes/public/gfxWindowsNativeDrawing.h b/gfx/thebes/public/gfxWindowsNativeDrawing.h
--- a/gfx/thebes/public/gfxWindowsNativeDrawing.h
+++ b/gfx/thebes/public/gfxWindowsNativeDrawing.h
@@ -128,7 +128,7 @@ public:
 
 private:
 
-    nsRefPtr<gfxContext> mContext;
+    RefPtr<gfxContext> mContext;
     gfxRect mNativeRect;
     PRUint32 mNativeDrawFlags;
 
@@ -136,7 +136,7 @@ private:
     PRUint8 mRenderState;
 
     gfxPoint mDeviceOffset;
-    nsRefPtr<gfxPattern> mBlackPattern, mWhitePattern;
+    RefPtr<gfxPattern> mBlackPattern, mWhitePattern;
 
     enum TransformType {
         TRANSLATION_ONLY,
@@ -150,7 +150,7 @@ private:
     XFORM mWorldTransform;
 
     // saved state
-    nsRefPtr<gfxWindowsSurface> mWinSurface, mBlackSurface, mWhiteSurface;
+    RefPtr<gfxWindowsSurface> mWinSurface, mBlackSurface, mWhiteSurface;
     HDC mDC;
     XFORM mOldWorldTransform;
     POINT mOrigViewportOrigin;
diff --git a/gfx/thebes/public/gfxWindowsPlatform.h b/gfx/thebes/public/gfxWindowsPlatform.h
--- a/gfx/thebes/public/gfxWindowsPlatform.h
+++ b/gfx/thebes/public/gfxWindowsPlatform.h
@@ -57,8 +57,8 @@ public:
         return (gfxWindowsPlatform*) gfxPlatform::GetPlatform();
     }
 
-    already_AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
-                                                         gfxASurface::gfxImageFormat imageFormat);
+    AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
+                                                           gfxASurface::gfxImageFormat imageFormat);
 
     nsresult GetFontList(const nsACString& aLangGroup,
                          const nsACString& aGenericFamily,
@@ -93,7 +93,7 @@ public:
     PRBool GetPrefFontEntries(const nsCString& aLangGroup, nsTArray<nsRefPtr<FontEntry> > *array);
     void SetPrefFontEntries(const nsCString& aLangGroup, nsTArray<nsRefPtr<FontEntry> >& array);
 
-    typedef nsDataHashtable<nsStringHashKey, nsRefPtr<FontFamily> > FontTable;
+    typedef nsDataHashtable<nsStringHashKey, RefPtr<FontFamily> > FontTable;
 
 private:
     void Init();
@@ -112,7 +112,7 @@ private:
                                                          void* userArg);
 
     static PLDHashOperator PR_CALLBACK FontGetCMapDataProc(nsStringHashKey::KeyType aKey,
-                                                           nsRefPtr<FontFamily>& aFontFamily,
+                                                           RefPtr<FontFamily>& aFontFamily,
                                                            void* userArg);
 
     static int CALLBACK FontResolveProc(const ENUMLOGFONTEXW *lpelfe,
@@ -120,12 +120,12 @@ private:
                                         DWORD fontType, LPARAM data);
 
     static PLDHashOperator PR_CALLBACK HashEnumFunc(nsStringHashKey::KeyType aKey,
-                                                    nsRefPtr<FontFamily>& aData,
+                                                    RefPtr<FontFamily>& aData,
                                                     void* userArg);
 
     static PLDHashOperator PR_CALLBACK FindFontForCharProc(nsStringHashKey::KeyType aKey,
-                                                             nsRefPtr<FontFamily>& aFontFamily,
-                                                             void* userArg);
+                                                           RefPtr<FontFamily>& aFontFamily,
+                                                           void* userArg);
 
     virtual cmsHPROFILE GetPlatformCMSOutputProfile();
 
diff --git a/gfx/thebes/public/gfxWindowsSurface.h b/gfx/thebes/public/gfxWindowsSurface.h
--- a/gfx/thebes/public/gfxWindowsSurface.h
+++ b/gfx/thebes/public/gfxWindowsSurface.h
@@ -68,11 +68,11 @@ public:
 
     HDC GetDC() { return mDC; }
 
-    already_AddRefed<gfxImageSurface> GetImageSurface();
+    AddRefed<gfxImageSurface> GetImageSurface();
 
-    already_AddRefed<gfxWindowsSurface> OptimizeToDDB(HDC dc,
-                                                      const gfxIntSize& size,
-                                                      gfxImageFormat format);
+    AddRefed<gfxWindowsSurface> OptimizeToDDB(HDC dc,
+                                                        const gfxIntSize& size,
+                                                        gfxImageFormat format);
 
     nsresult BeginPrinting(const nsAString& aTitle, const nsAString& aPrintToFileName);
     nsresult EndPrinting();
diff --git a/gfx/thebes/public/gfxXlibNativeRenderer.h b/gfx/thebes/public/gfxXlibNativeRenderer.h
--- a/gfx/thebes/public/gfxXlibNativeRenderer.h
+++ b/gfx/thebes/public/gfxXlibNativeRenderer.h
@@ -89,7 +89,7 @@ public:
     };
 
     struct DrawOutput {
-        nsRefPtr<gfxASurface> mSurface;
+        mozilla::RefPtr<gfxASurface> mSurface;
         PRPackedBool mUniformAlpha;
         PRPackedBool mUniformColor;
         gfxRGBA      mColor;
diff --git a/gfx/thebes/src/gfxASurface.cpp b/gfx/thebes/src/gfxASurface.cpp
--- a/gfx/thebes/src/gfxASurface.cpp
+++ b/gfx/thebes/src/gfxASurface.cpp
@@ -58,12 +58,14 @@
 #include <stdio.h>
 #include <limits.h>
 
+using namespace mozilla;
+
 static cairo_user_data_key_t gfxasurface_pointer_key;
 
 // Surfaces use refcounting that's tied to the cairo surface refcnt, to avoid
 // refcount mismatch issues.
-nsrefcnt
-gfxASurface::AddRef(void)
+void
+gfxASurface::AddReference()
 {
     if (mSurfaceValid) {
         if (mFloatingRefs) {
@@ -72,17 +74,15 @@ gfxASurface::AddRef(void)
         } else {
             cairo_surface_reference(mSurface);
         }
-
-        return (nsrefcnt) cairo_surface_get_reference_count(mSurface);
     } else {
         // the surface isn't valid, but we still need to refcount
         // the gfxASurface
-        return ++mFloatingRefs;
+        ++mFloatingRefs;
     }
 }
 
-nsrefcnt
-gfxASurface::Release(void)
+void
+gfxASurface::ReleaseReference(void)
 {
     if (mSurfaceValid) {
         NS_ASSERTION(mFloatingRefs == 0, "gfxASurface::Release with floating refs still hanging around!");
@@ -90,20 +90,21 @@ gfxASurface::Release(void)
         // Note that there is a destructor set on user data for mSurface,
         // which will delete this gfxASurface wrapper when the surface's refcount goes
         // out of scope.
-        nsrefcnt refcnt = (nsrefcnt) cairo_surface_get_reference_count(mSurface);
         cairo_surface_destroy(mSurface);
-
-        // |this| may not be valid any more, don't use it!
-
-        return --refcnt;
     } else {
         if (--mFloatingRefs == 0) {
             delete this;
-            return 0;
         }
+    }
+}
 
-        return mFloatingRefs;
+uint32_t
+gfxASurface::GetRefCount()
+{
+    if (mSurfaceValid) {
+        return cairo_surface_get_reference_count(mSurface);
     }
+    return mFloatingRefs;
 }
 
 void
@@ -125,7 +126,7 @@ gfxASurface::SetSurfaceWrapper(cairo_sur
     cairo_surface_set_user_data(csurf, &gfxasurface_pointer_key, asurf, SurfaceDestroyFunc);
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxASurface::Wrap (cairo_surface_t *csurf)
 {
     gfxASurface *result;
@@ -134,8 +135,7 @@ gfxASurface::Wrap (cairo_surface_t *csur
     result = GetSurfaceWrapper(csurf);
     if (result) {
         // fprintf(stderr, "Existing wrapper for %p -> %p\n", csurf, result);
-        NS_ADDREF(result);
-        return result;
+        return do_AddRef(result);
     }
 
     /* No wrapper; figure out the surface type and create it */
@@ -169,8 +169,7 @@ gfxASurface::Wrap (cairo_surface_t *csur
 
     // fprintf(stderr, "New wrapper for %p -> %p\n", csurf, result);
 
-    NS_ADDREF(result);
-    return result;
+    return do_AddRef(result);
 }
 
 void
diff --git a/gfx/thebes/src/gfxAlphaRecovery.cpp b/gfx/thebes/src/gfxAlphaRecovery.cpp
--- a/gfx/thebes/src/gfxAlphaRecovery.cpp
+++ b/gfx/thebes/src/gfxAlphaRecovery.cpp
@@ -40,6 +40,7 @@
 
 #include "gfxImageSurface.h"
 
+using namespace mozilla;
 
 struct gfxAlphaRecoveryResult {
     gfxAlphaRecoveryResult()
@@ -57,14 +58,14 @@ static void _compute_alpha_values (unsig
                                    gfxIntSize dimensions,
                                    gfxAlphaRecoveryResult *result);
 
-already_AddRefed<gfxImageSurface>
+AddRefed<gfxImageSurface>
 gfxAlphaRecovery::RecoverAlpha (gfxImageSurface *blackSurf,
                                 gfxImageSurface *whiteSurf,
                                 gfxIntSize dimensions)
 {
 
-    nsRefPtr<gfxImageSurface> resultSurf;
-    resultSurf = new gfxImageSurface(dimensions, gfxASurface::ImageFormatARGB32);
+    RefPtr<gfxImageSurface> resultSurf =
+      new gfxImageSurface(dimensions, gfxASurface::ImageFormatARGB32);
 
     // copy blackSurf into resultSurf
     gfxContext ctx(resultSurf);
@@ -80,8 +81,7 @@ gfxAlphaRecovery::RecoverAlpha (gfxImage
 
     // XX use result, maybe return pattern, etc.
 
-    NS_ADDREF(resultSurf.get());
-    return resultSurf.get();
+    return resultSurf.forget();
 }
 
 /** from cairo-xlib-utils.c, modified */
diff --git a/gfx/thebes/src/gfxAtsuiFonts.cpp b/gfx/thebes/src/gfxAtsuiFonts.cpp
--- a/gfx/thebes/src/gfxAtsuiFonts.cpp
+++ b/gfx/thebes/src/gfxAtsuiFonts.cpp
@@ -440,25 +440,24 @@ gfxAtsuiFont::GetFontEntry()
  * except for OOM in which case we do nothing and return null.
  */
  
-static already_AddRefed<gfxAtsuiFont>
+static AddRefed<gfxAtsuiFont>
 GetOrMakeFont(MacOSFontEntry *aFontEntry, const gfxFontStyle *aStyle, PRBool aNeedsBold)
 {
     // the font entry name is the psname, not the family name
-    nsRefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aFontEntry->Name(), aStyle);
+    RefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aFontEntry->Name(), aStyle);
     if (!font) {
         gfxAtsuiFont *newFont = new gfxAtsuiFont(aFontEntry, aStyle, aNeedsBold);
         if (!newFont)
-            return nsnull;
+            return AddRefed<gfxAtsuiFont>(nsnull);
         if (!newFont->Valid()) {
             delete newFont;
-            return nsnull;
+            return AddRefed<gfxAtsuiFont>(nsnull);
         }
         font = newFont;
         gfxFontCache::GetCache()->AddNew(font);
     }
-    gfxFont *f = nsnull;
-    font.swap(f);
-    return static_cast<gfxAtsuiFont *>(f);
+
+    return AddRefed<gfxAtsuiFont>(static_cast<gfxAtsuiFont*>(font.forget().get()));
 }
 
 gfxAtsuiFontGroup::gfxAtsuiFontGroup(const nsAString& families,
@@ -484,7 +483,7 @@ gfxAtsuiFontGroup::gfxAtsuiFontGroup(con
         MacOSFontEntry *defaultFont = gfxQuartzFontCache::SharedFontCache()->GetDefaultFont(aStyle, needsBold);
         NS_ASSERTION(defaultFont, "invalid default font returned by GetDefaultFont");
 
-        nsRefPtr<gfxAtsuiFont> font = GetOrMakeFont(defaultFont, aStyle, needsBold);
+        RefPtr<gfxAtsuiFont> font = GetOrMakeFont(defaultFont, aStyle, needsBold);
 
         if (font) {
             mFonts.AppendElement(font);
@@ -520,7 +519,7 @@ gfxAtsuiFontGroup::FindATSUFont(const ns
     MacOSFontEntry *fe = fc->FindFontForFamily(aName, fontStyle, needsBold);
 
     if (fe && !fontGroup->HasFont(fe->GetFontID())) {
-        nsRefPtr<gfxAtsuiFont> font = GetOrMakeFont(fe, fontStyle, needsBold);
+        RefPtr<gfxAtsuiFont> font = GetOrMakeFont(fe, fontStyle, needsBold);
         if (font) {
             fontGroup->mFonts.AppendElement(font);
         }
@@ -770,11 +769,11 @@ gfxAtsuiFontGroup::HasFont(ATSUFontID fi
 }
 
 struct PrefFontCallbackData {
-    PrefFontCallbackData(nsTArray<nsRefPtr<MacOSFamilyEntry> >& aFamiliesArray) 
+    PrefFontCallbackData(nsTArray<RefPtr<MacOSFamilyEntry> >& aFamiliesArray) 
         : mPrefFamilies(aFamiliesArray)
     {}
 
-    nsTArray<nsRefPtr<MacOSFamilyEntry> >& mPrefFamilies;
+    nsTArray<RefPtr<MacOSFamilyEntry> >& mPrefFamilies;
 
     static PRBool AddFontFamilyEntry(eFontPrefLang aLang, const nsAString& aName, void *aClosure)
     {
@@ -789,12 +788,12 @@ struct PrefFontCallbackData {
 };
 
 
-already_AddRefed<gfxAtsuiFont>
+AddRefed<gfxAtsuiFont>
 gfxAtsuiFontGroup::WhichPrefFontSupportsChar(PRUint32 aCh)
 {
     // FindCharUnicodeRange only supports BMP character points and there are no non-BMP fonts in prefs
     if (aCh > 0xFFFF)
-        return nsnull;
+        return AddRefed<gfxAtsuiFont>(nsnull);
 
     // get the pref font list if it hasn't been set up already
     PRUint32 unicodeRange = FindCharUnicodeRange(aCh);
@@ -802,7 +801,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
 
     // if the last pref font was the first family in the pref list, no need to recheck through a list of families
     if (mLastPrefFont && charLang == mLastPrefLang && mLastPrefFirstFont && mLastPrefFont->TestCharacterMap(aCh)) {
-        nsRefPtr<gfxAtsuiFont> prefFont = mLastPrefFont;
+        RefPtr<gfxAtsuiFont> prefFont = mLastPrefFont;
         return prefFont.forget();
     }
     
@@ -814,7 +813,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
     macPlatform->GetLangPrefs(prefLangs, numLangs, charLang, mPageLang);
     
     for (i = 0; i < numLangs; i++) {
-        nsAutoTArray<nsRefPtr<MacOSFamilyEntry>, 5> families;
+        nsAutoTArray<RefPtr<MacOSFamilyEntry>, 5> families;
         eFontPrefLang currentLang = prefLangs[i];
         
         gfxQuartzFontCache *fc = gfxQuartzFontCache::SharedFontCache();
@@ -841,7 +840,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
             // GetOrMakeFont repeatedly.  speeds up FindFontForChar lookup times for subsequent
             // pref font lookups
             if (family == mLastPrefFamily && mLastPrefFont->TestCharacterMap(aCh)) {
-                nsRefPtr<gfxAtsuiFont> prefFont = mLastPrefFont;
+                RefPtr<gfxAtsuiFont> prefFont = mLastPrefFont;
                 return prefFont.forget();
             }
             
@@ -849,7 +848,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
             MacOSFontEntry *fe = family->FindFont(&mStyle, needsBold);
             // if ch in cmap, create and return a gfxFont
             if (fe && fe->TestCharacterMap(aCh)) {
-                nsRefPtr<gfxAtsuiFont> prefFont = GetOrMakeFont(fe, &mStyle, needsBold);
+                RefPtr<gfxAtsuiFont> prefFont = GetOrMakeFont(fe, &mStyle, needsBold);
                 if (!prefFont) continue;
                 mLastPrefFamily = family;
                 mLastPrefFont = prefFont;
@@ -861,13 +860,13 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
         }
     }
     
-    return nsnull;
+    return AddRefed<gfxAtsuiFont>(nsnull);
 }
 
-already_AddRefed<gfxAtsuiFont>
+AddRefed<gfxAtsuiFont>
 gfxAtsuiFontGroup::FindFontForChar(PRUint32 aCh, PRUint32 aPrevCh, PRUint32 aNextCh, gfxAtsuiFont* aPrevMatchedFont)
 {
-    nsRefPtr<gfxAtsuiFont>    selectedFont;
+    RefPtr<gfxAtsuiFont>    selectedFont;
     
     // if this character or the next one is a joiner use the
     // same font as the previous range if we can
@@ -912,7 +911,7 @@ gfxAtsuiFontGroup::FindFontForChar(PRUin
         }
     }
 
-    return nsnull;
+    return AddRefed<gfxAtsuiFont>(nsnull);
 }
 
 /**
@@ -1370,7 +1369,7 @@ public:
     PRUint32 MatchNextRange() 
     { 
         PRUint32                matchStartOffset, chStartOffset, ch, nextCh;
-        nsRefPtr<gfxAtsuiFont>  font;
+        RefPtr<gfxAtsuiFont>  font;
         
         matchStartOffset = mPrevOffset;
 
@@ -1429,8 +1428,8 @@ private:
     PRUint32                mPrevCh;
     PRBool                  mFirstRange;
     gfxAtsuiFontGroup       *mFontGroup;
-    nsRefPtr<gfxAtsuiFont>  mMatchedFont;
-    nsRefPtr<gfxAtsuiFont>  mNextMatchedFont;
+    RefPtr<gfxAtsuiFont> mMatchedFont;
+    RefPtr<gfxAtsuiFont> mNextMatchedFont;
 };
 
 
diff --git a/gfx/thebes/src/gfxBeOSPlatform.cpp b/gfx/thebes/src/gfxBeOSPlatform.cpp
--- a/gfx/thebes/src/gfxBeOSPlatform.cpp
+++ b/gfx/thebes/src/gfxBeOSPlatform.cpp
@@ -66,7 +66,7 @@ gfxBeOSPlatform::~gfxBeOSPlatform()
 #endif
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxBeOSPlatform::CreateOffscreenSurface (PRUint32 width,
                                          PRUint32 height,
                                          gfxASurface::gfxImageFormat imageFormat)
diff --git a/gfx/thebes/src/gfxContext.cpp b/gfx/thebes/src/gfxContext.cpp
--- a/gfx/thebes/src/gfxContext.cpp
+++ b/gfx/thebes/src/gfxContext.cpp
@@ -56,6 +56,7 @@
 #include "gfxPattern.h"
 #include "gfxPlatform.h"
 
+using namespace mozilla;
 
 gfxContext::gfxContext(gfxASurface *surface) :
     mSurface(surface)
@@ -74,16 +75,14 @@ gfxContext::OriginalSurface()
     return mSurface;
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxContext::CurrentSurface(gfxFloat *dx, gfxFloat *dy)
 {
     cairo_surface_t *s = cairo_get_group_target(mCairo);
     if (s == mSurface->CairoSurface()) {
         if (dx && dy)
             cairo_surface_get_device_offset(s, dx, dy);
-        gfxASurface *ret = mSurface;
-        NS_ADDREF(ret);
-        return ret;
+        return do_AddRef(mSurface);
     }
 
     if (dx && dy)
@@ -673,7 +672,7 @@ gfxContext::SetPattern(gfxPattern *patte
     cairo_set_source(mCairo, pattern->CairoPattern());
 }
 
-already_AddRefed<gfxPattern>
+AddRefed<gfxPattern>
 gfxContext::GetPattern()
 {
     cairo_pattern_t *pat = cairo_get_source(mCairo);
@@ -685,8 +684,7 @@ gfxContext::GetPattern()
     else
         wrapper = new gfxPattern(gfxRGBA(0,0,0,0));
 
-    NS_IF_ADDREF(wrapper);
-    return wrapper;
+    return do_AddRef(wrapper);
 }
 
 
@@ -718,14 +716,13 @@ gfxContext::PushGroup(gfxASurface::gfxCo
     cairo_push_group_with_content(mCairo, (cairo_content_t) content);
 }
 
-already_AddRefed<gfxPattern>
+AddRefed<gfxPattern>
 gfxContext::PopGroup()
 {
     cairo_pattern_t *pat = cairo_pop_group(mCairo);
     gfxPattern *wrapper = new gfxPattern(pat);
     cairo_pattern_destroy(pat);
-    NS_IF_ADDREF(wrapper);
-    return wrapper;
+    return do_AddRef(wrapper);
 }
 
 void
@@ -770,13 +767,12 @@ gfxContext::GetUserStrokeExtent()
     return gfxRect(xmin, ymin, xmax - xmin, ymax - ymin);
 }
 
-already_AddRefed<gfxFlattenedPath>
+AddRefed<gfxFlattenedPath>
 gfxContext::GetFlattenedPath()
 {
     gfxFlattenedPath *path =
         new gfxFlattenedPath(cairo_copy_path_flat(mCairo));
-    NS_IF_ADDREF(path);
-    return path;
+    return do_AddRef(path);
 }
 
 PRBool
diff --git a/gfx/thebes/src/gfxFont.cpp b/gfx/thebes/src/gfxFont.cpp
--- a/gfx/thebes/src/gfxFont.cpp
+++ b/gfx/thebes/src/gfxFont.cpp
@@ -55,6 +55,8 @@
 
 #include "nsCRT.h"
 
+using namespace mozilla;
+
 gfxFontCache *gfxFontCache::gGlobalCache = nsnull;
 
 #ifdef DEBUG_roc
@@ -107,18 +109,16 @@ gfxFontCache::HashEntry::KeyEquals(const
            aKey->mStyle->Equals(*mFont->GetStyle());
 }
 
-already_AddRefed<gfxFont>
+AddRefed<gfxFont>
 gfxFontCache::Lookup(const nsAString &aName,
                      const gfxFontStyle *aStyle)
 {
     Key key(aName, aStyle);
     HashEntry *entry = mFonts.GetEntry(key);
     if (!entry)
-        return nsnull;
+        return AddRefed<gfxFont>(nsnull);
 
-    gfxFont *font = entry->mFont;
-    NS_ADDREF(font);
-    return font;
+    return do_AddRef(entry->mFont);
 }
 
 void
@@ -1087,7 +1087,6 @@ gfxTextRun::gfxTextRun(const gfxTextRunF
 {
     NS_ASSERTION(mAppUnitsPerDevUnit != 0, "Invalid app unit scale");
     MOZ_COUNT_CTOR(gfxTextRun);
-    NS_ADDREF(mFontGroup);
     if (aParams->mSkipChars) {
         mSkipChars.TakeFrom(aParams->mSkipChars);
     }
@@ -1121,7 +1120,6 @@ gfxTextRun::~gfxTextRun()
 #ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
     AccountStorageForTextRun(this, -1);
 #endif
-    NS_RELEASE(mFontGroup);
     MOZ_COUNT_DTOR(gfxTextRun);
 }
 
diff --git a/gfx/thebes/src/gfxFontconfigUtils.cpp b/gfx/thebes/src/gfxFontconfigUtils.cpp
--- a/gfx/thebes/src/gfxFontconfigUtils.cpp
+++ b/gfx/thebes/src/gfxFontconfigUtils.cpp
@@ -46,6 +46,8 @@
 
 #include "nsIAtom.h"
 #include "nsCRT.h"
+
+using namespace mozilla;
 
 /* static */ gfxFontconfigUtils* gfxFontconfigUtils::sUtils = nsnull;
 
@@ -309,7 +311,7 @@ gfxFontconfigUtils::UpdateFontListIntern
         return NS_OK;
 
     for (PRInt32 i = 0; i < mAliasForMultiFonts.Count(); i++) {
-        nsRefPtr<gfxFontNameList> fonts = new gfxFontNameList;
+        RefPtr<gfxFontNameList> fonts = new gfxFontNameList;
         nsCAutoString fontname(*mAliasForMultiFonts.CStringAt(i));
         rv = GetResolvedFonts(fontname, fonts);
         if (NS_FAILED(rv))
@@ -497,7 +499,7 @@ gfxFontconfigUtils::ResolveFontName(cons
     if (mAliasForMultiFonts.IndexOfIgnoreCase(fontname) >= 0) {
         nsCAutoString key;
         ToLowerCase(fontname, key);
-        nsRefPtr<gfxFontNameList> fonts;
+        RefPtr<gfxFontNameList> fonts;
         if (!mAliasTable.Get(key, &fonts))
             NS_ERROR("The mAliasTable was broken!");
         for (PRUint32 i = 0; i < fonts->Length(); i++) {
diff --git a/gfx/thebes/src/gfxFontconfigUtils.h b/gfx/thebes/src/gfxFontconfigUtils.h
--- a/gfx/thebes/src/gfxFontconfigUtils.h
+++ b/gfx/thebes/src/gfxFontconfigUtils.h
@@ -46,7 +46,7 @@ class gfxFontNameList : public nsTArray<
 class gfxFontNameList : public nsTArray<nsString>
 {
 public:
-    THEBES_INLINE_DECL_REFCOUNTING(gfxFontList)
+    DECL_INLINE_REFCOUNTING(gfxFontList)
     PRBool Exists(nsAString& aName);
 };
 
@@ -93,7 +93,7 @@ protected:
     nsCStringArray mAliasForSingleFont;
     nsCStringArray mAliasForMultiFonts;
 
-    nsDataHashtable<nsCStringHashKey, nsRefPtr<gfxFontNameList> > mAliasTable;
+    nsDataHashtable<nsCStringHashKey, mozilla::RefPtr<gfxFontNameList> > mAliasTable;
 };
 
 #endif /* GFX_FONTCONFIG_UTILS_H */
diff --git a/gfx/thebes/src/gfxImageSurface.cpp b/gfx/thebes/src/gfxImageSurface.cpp
--- a/gfx/thebes/src/gfxImageSurface.cpp
+++ b/gfx/thebes/src/gfxImageSurface.cpp
@@ -40,6 +40,8 @@
 #include "gfxImageSurface.h"
 
 #include "cairo.h"
+
+#include <string.h>
 
 gfxImageSurface::gfxImageSurface(unsigned char *aData, const gfxIntSize& aSize,
                                  long aStride, gfxImageFormat aFormat)
diff --git a/gfx/thebes/src/gfxOS2Fonts.cpp b/gfx/thebes/src/gfxOS2Fonts.cpp
--- a/gfx/thebes/src/gfxOS2Fonts.cpp
+++ b/gfx/thebes/src/gfxOS2Fonts.cpp
@@ -424,10 +424,10 @@ PRBool gfxOS2Font::SetupCairoFont(gfxCon
  * In either case, add a ref and return it ---
  * except for OOM in which case we do nothing and return null.
  */
-static already_AddRefed<gfxOS2Font> GetOrMakeFont(const nsAString& aName,
+static AddRefed<gfxOS2Font> GetOrMakeFont(const nsAString& aName,
                                                   const gfxFontStyle *aStyle)
 {
-    nsRefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aName, aStyle);
+    RefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aName, aStyle);
     if (!font) {
         font = new gfxOS2Font(aName, aStyle);
         if (!font)
@@ -477,7 +477,7 @@ gfxOS2FontGroup::gfxOS2FontGroup(const n
     }
 
     for (int i = 0; i < familyArray.Count(); i++) {
-        nsRefPtr<gfxOS2Font> font = GetOrMakeFont(*familyArray[i], &mStyle);
+        RefPtr<gfxOS2Font> font = GetOrMakeFont(*familyArray[i], &mStyle);
         if (font) {
             mFonts.AppendElement(font);
         }
@@ -506,7 +506,7 @@ gfxOS2FontGroup::gfxOS2FontGroup(const n
         for (int i = 3; i < fontList.Count(); i++) {
             // check for duplicates that we already found through the familyArray
             if (familyArray.IndexOf(*fontList[i]) == -1) {
-                nsRefPtr<gfxOS2Font> font = GetOrMakeFont(*fontList[i], &mStyle);
+                RefPtr<gfxOS2Font> font = GetOrMakeFont(*fontList[i], &mStyle);
                 if (font) {
                     mFonts.AppendElement(font);
                 }
diff --git a/gfx/thebes/src/gfxOS2Platform.cpp b/gfx/thebes/src/gfxOS2Platform.cpp
--- a/gfx/thebes/src/gfxOS2Platform.cpp
+++ b/gfx/thebes/src/gfxOS2Platform.cpp
@@ -81,7 +81,7 @@ gfxOS2Platform::~gfxOS2Platform()
 #endif
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxOS2Platform::CreateOffscreenSurface(const gfxIntSize& aSize,
                                        gfxASurface::gfxImageFormat aImageFormat)
 {
diff --git a/gfx/thebes/src/gfxPangoFonts.cpp b/gfx/thebes/src/gfxPangoFonts.cpp
--- a/gfx/thebes/src/gfxPangoFonts.cpp
+++ b/gfx/thebes/src/gfxPangoFonts.cpp
@@ -78,6 +78,8 @@
 #include <gdk/gdkpango.h>
 
 #include <math.h>
+
+using namespace mozilla;
 
 #define FLOAT_PANGO_SCALE ((gfxFloat)PANGO_SCALE)
 
@@ -483,19 +485,17 @@ gfxPangoFontGroup::FontCallback (const n
  * In either case, add a ref, append it to the aFonts array, and return it ---
  * except for OOM in which case we do nothing and return null.
  */
-static already_AddRefed<gfxPangoFont>
+static AddRefed<gfxPangoFont>
 GetOrMakeFont(const nsAString& aName, const gfxFontStyle *aStyle)
 {
-    nsRefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aName, aStyle);
+    RefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aName, aStyle);
     if (!font) {
         font = new gfxPangoFont(aName, aStyle);
         if (!font)
-            return nsnull;
+            return AddRefed<gfxPangoFont>(NULL);
         gfxFontCache::GetCache()->AddNew(font);
     }
-    gfxFont *f = nsnull;
-    font.swap(f);
-    return static_cast<gfxPangoFont *>(f);
+    return do_AddRef(static_cast<gfxPangoFont*>(font.get()));
 }
 
 gfxPangoFontGroup::gfxPangoFontGroup (const nsAString& families,
@@ -532,7 +532,7 @@ gfxPangoFontGroup::gfxPangoFontGroup (co
         fcFamilies.Append(NS_LITERAL_STRING("sans-serif"));
     }
 
-    nsRefPtr<gfxPangoFont> font = GetOrMakeFont(fcFamilies, &mStyle);
+    RefPtr<gfxPangoFont> font = GetOrMakeFont(fcFamilies, &mStyle);
     if (font) {
         mFonts.AppendElement(font);
     }
@@ -714,7 +714,7 @@ NewPangoFontDescription(const nsAString 
  */
 
 /* static */
-already_AddRefed<gfxPangoFont>
+AddRefed<gfxPangoFont>
 gfxPangoFont::GetOrMakeFont(PangoFont *aPangoFont)
 {
     gfxPangoFont *font = static_cast<gfxPangoFont*>
@@ -747,13 +747,12 @@ gfxPangoFont::GetOrMakeFont(PangoFont *a
 
         pango_font_description_free(desc);
         if (!font)
-            return nsnull;
+            return AddRefed<gfxPangoFont>(NULL);
 
         // Do not add this font to the gfxFontCache hash table as this may not
         // be the PangoFont that fontconfig chooses for this style.
     }
-    NS_ADDREF(font);
-    return font;
+    return do_AddRef(font);
 }
 
 static PangoFont*
@@ -1657,7 +1656,7 @@ gfxPangoFontGroup::CreateGlyphRunsItemiz
         }
 
         /* look up the gfxPangoFont from the PangoFont */
-        nsRefPtr<gfxPangoFont> font =
+        RefPtr<gfxPangoFont> font =
             gfxPangoFont::GetOrMakeFont(item->analysis.font);
 
         nsresult rv = aTextRun->AddGlyphRun(font, utf16Offset, PR_TRUE);
diff --git a/gfx/thebes/src/gfxPattern.cpp b/gfx/thebes/src/gfxPattern.cpp
--- a/gfx/thebes/src/gfxPattern.cpp
+++ b/gfx/thebes/src/gfxPattern.cpp
@@ -42,6 +42,8 @@
 
 #include "cairo.h"
 #include "lcms.h"
+
+using namespace mozilla;
 
 gfxPattern::gfxPattern(cairo_pattern_t *aPattern)
 {
@@ -160,13 +162,13 @@ gfxPattern::GetSolidColor(gfxRGBA& aColo
                                   &aColor.a) == CAIRO_STATUS_SUCCESS;
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxPattern::GetSurface()
 {
     cairo_surface_t *surf = nsnull;
 
     if (cairo_pattern_get_surface (mPattern, &surf) != CAIRO_STATUS_SUCCESS)
-        return nsnull;
+        return AddRefed<gfxASurface>(NULL);
 
     return gfxASurface::Wrap(surf);
 }
diff --git a/gfx/thebes/src/gfxPlatform.cpp b/gfx/thebes/src/gfxPlatform.cpp
--- a/gfx/thebes/src/gfxPlatform.cpp
+++ b/gfx/thebes/src/gfxPlatform.cpp
@@ -68,6 +68,8 @@
 #include "plstr.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
+
+using namespace mozilla;
 
 gfxPlatform *gPlatform = nsnull;
 int gGlitzState = -1;
@@ -232,24 +234,22 @@ gfxPlatform::SetUseGlitz(PRBool use)
     gGlitzState = (use ? 1 : 0);
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxPlatform::OptimizeImage(gfxImageSurface *aSurface,
                            gfxASurface::gfxImageFormat format)
 {
     const gfxIntSize& surfaceSize = aSurface->GetSize();
 
-    nsRefPtr<gfxASurface> optSurface = CreateOffscreenSurface(surfaceSize, format);
+    RefPtr<gfxASurface> optSurface(CreateOffscreenSurface(surfaceSize, format));
     if (!optSurface || optSurface->CairoStatus() != 0)
-        return nsnull;
+        return AddRefed<gfxASurface>(NULL);
 
     gfxContext tmpCtx(optSurface);
     tmpCtx.SetOperator(gfxContext::OPERATOR_SOURCE);
     tmpCtx.SetSource(aSurface);
     tmpCtx.Paint();
 
-    gfxASurface *ret = optSurface;
-    NS_ADDREF(ret);
-    return ret;
+    return do_AddRef(optSurface);
 }
 
 nsresult
diff --git a/gfx/thebes/src/gfxPlatformGtk.cpp b/gfx/thebes/src/gfxPlatformGtk.cpp
--- a/gfx/thebes/src/gfxPlatformGtk.cpp
+++ b/gfx/thebes/src/gfxPlatformGtk.cpp
@@ -66,6 +66,8 @@
 
 #include "lcms.h"
 
+using namespace mozilla;
+
 PRInt32 gfxPlatformGtk::sDPI = -1;
 gfxFontconfigUtils *gfxPlatformGtk::sFontconfigUtils = nsnull;
 
@@ -104,11 +106,11 @@ gfxPlatformGtk::~gfxPlatformGtk()
 #endif
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxPlatformGtk::CreateOffscreenSurface(const gfxIntSize& size,
                                        gfxASurface::gfxImageFormat imageFormat)
 {
-    nsRefPtr<gfxASurface> newSurface = nsnull;
+    RefPtr<gfxASurface> newSurface = nsnull;
 
     int glitzf;
     int xrenderFormatID;
@@ -130,7 +132,7 @@ gfxPlatformGtk::CreateOffscreenSurface(c
             xrenderFormatID = PictStandardA1;
             break;
         default:
-            return nsnull;
+            return AddRefed<gfxASurface>(nsnull);
     }
 
     // XXX we really need a different interface here, something that passes
@@ -138,7 +140,7 @@ gfxPlatformGtk::CreateOffscreenSurface(c
     // we should try to match
     Display* display = GDK_DISPLAY();
     if (!display)
-        return nsnull;
+        return AddRefed<gfxASurface>(nsnull);
 
     if (!UseGlitz()) {
         GdkPixmap* pixmap = nsnull;
diff --git a/gfx/thebes/src/gfxPlatformMac.cpp b/gfx/thebes/src/gfxPlatformMac.cpp
--- a/gfx/thebes/src/gfxPlatformMac.cpp
+++ b/gfx/thebes/src/gfxPlatformMac.cpp
@@ -68,7 +68,7 @@ gfxPlatformMac::gfxPlatformMac()
     mFontAntiAliasingThreshold = ReadAntiAliasingThreshold();
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxPlatformMac::CreateOffscreenSurface(const gfxIntSize& size,
                                        gfxASurface::gfxImageFormat imageFormat)
 {
@@ -143,28 +143,25 @@ gfxPlatformMac::CreateOffscreenSurface(c
 #endif
     }
 
-    NS_IF_ADDREF(newSurface);
-    return newSurface;
+    return do_AddRef(newSurface);
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxPlatformMac::OptimizeImage(gfxImageSurface *aSurface,
                               gfxASurface::gfxImageFormat format)
 {
     const gfxIntSize& surfaceSize = aSurface->GetSize();
-    nsRefPtr<gfxImageSurface> isurf = aSurface;
+    RefPtr<gfxImageSurface> isurf = aSurface;
 
     if (format != aSurface->Format()) {
         isurf = new gfxImageSurface (surfaceSize, format);
         if (!isurf->CopyFrom (aSurface)) {
             // don't even bother doing anything more
-            NS_ADDREF(aSurface);
-            return aSurface;
+            return do_AddRef(static_cast<gfxASurface*>(aSurface));
         }
     }
 
-    nsRefPtr<gfxASurface> ret = new gfxQuartzImageSurface(isurf);
-    return ret.forget();
+    return do_AddRef(static_cast<gfxASurface*>(new gfxQuartzImageSurface(isurf)));
 }
 
 nsresult
diff --git a/gfx/thebes/src/gfxQuartzFontCache.h b/gfx/thebes/src/gfxQuartzFontCache.h
--- a/gfx/thebes/src/gfxQuartzFontCache.h
+++ b/gfx/thebes/src/gfxQuartzFontCache.h
@@ -41,7 +41,6 @@
 #define GFXQUARTZFONTCACHE_H_
 
 #include "nsDataHashtable.h"
-#include "nsRefPtrHashtable.h"
 
 #include "gfxFontUtils.h"
 #include "gfxAtsuiFonts.h"
@@ -60,7 +59,7 @@ struct FontSearch {
     const PRUint32 ch;
     gfxAtsuiFont *fontToMatch;
     PRInt32 matchRank;
-    nsRefPtr<MacOSFontEntry> bestMatch;
+    RefPtr<MacOSFontEntry> bestMatch;
 };
 
 class MacOSFamilyEntry;
@@ -130,9 +129,9 @@ public:
     virtual void LocalizedName(nsAString& aLocalizedName);
     virtual PRBool HasOtherFamilyNames();
     
-    nsTArray<nsRefPtr<MacOSFontEntry> >& GetFontList() { return mAvailableFonts; }
+    nsTArray<RefPtr<MacOSFontEntry> >& GetFontList() { return mAvailableFonts; }
     
-    void AddFontEntry(nsRefPtr<MacOSFontEntry> aFontEntry) {
+    void AddFontEntry(RefPtr<MacOSFontEntry> aFontEntry) {
         mAvailableFonts.AppendElement(aFontEntry);
     }
     
@@ -174,7 +173,7 @@ protected:
     MacOSFontEntry* FindFontWeight(MacOSFontEntry* aFontsForWeights[], const gfxFontStyle* aStyle, PRBool& aNeedsBold);
     
     nsString mName;  // canonical font family name returned from NSFontManager
-    nsTArray<nsRefPtr<MacOSFontEntry> >  mAvailableFonts;
+    nsTArray<RefPtr<MacOSFontEntry> >  mAvailableFonts;
     PRPackedBool mOtherFamilyNamesInitialized;
     PRPackedBool mHasOtherFamilyNames;
     PRPackedBool mIsBadUnderlineFontFamily;
@@ -236,15 +235,15 @@ public:
 
     static PRInt32 AppleWeightToCSSWeight(PRInt32 aAppleWeight);
     
-    PRBool GetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<nsRefPtr<MacOSFamilyEntry> > *array);
-    void SetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<nsRefPtr<MacOSFamilyEntry> >& array);
+    PRBool GetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<RefPtr<MacOSFamilyEntry> > *array);
+    void SetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<RefPtr<MacOSFamilyEntry> >& array);
     
     void AddOtherFamilyName(MacOSFamilyEntry *aFamilyEntry, nsAString& aOtherFamilyName);
 
 private:
     static PLDHashOperator PR_CALLBACK FindFontForCharProc(nsStringHashKey::KeyType aKey,
-                                                             nsRefPtr<MacOSFamilyEntry>& aFamilyEntry,
-                                                             void* userArg);
+                                                           RefPtr<MacOSFamilyEntry>& aFamilyEntry,
+                                                           void* userArg);
 
     static gfxQuartzFontCache *sSharedFontCache;
 
@@ -273,16 +272,16 @@ private:
     void SetFixedPitch(const nsAString& aFamilyName);
                                                              
     static PLDHashOperator PR_CALLBACK InitOtherFamilyNamesProc(nsStringHashKey::KeyType aKey,
-                                                             nsRefPtr<MacOSFamilyEntry>& aFamilyEntry,
-                                                             void* userArg);
-
+                                                                RefPtr<MacOSFamilyEntry>& aFamilyEntry,
+                                                                void* userArg);
+    
     void GenerateFontListKey(const nsAString& aKeyName, nsAString& aResult);
     static void ATSNotification(ATSFontNotificationInfoRef aInfo, void* aUserArg);
     static int PR_CALLBACK PrefChangedCallback(const char *aPrefName, void *closure);
 
     static PLDHashOperator PR_CALLBACK
         HashEnumFuncForFamilies(nsStringHashKey::KeyType aKey,
-                                nsRefPtr<MacOSFamilyEntry>& aFamilyEntry,
+                                RefPtr<MacOSFamilyEntry>& aFamilyEntry,
                                 void* aUserArg);
 
     // gfxFontInfoLoader overrides, used to load in font cmaps
@@ -291,15 +290,18 @@ private:
     virtual void FinishLoader();
 
     // canonical family name ==> family entry (unique, one name per family entry)
-    nsRefPtrHashtable<nsStringHashKey, MacOSFamilyEntry> mFontFamilies;    
+    nsDataHashtable< nsStringHashKey,
+                     RefPtr<MacOSFamilyEntry> > mFontFamilies;
 
     // other family name ==> family entry (not unique, can have multiple names per 
     // family entry, only names *other* than the canonical names are stored here)
-    nsRefPtrHashtable<nsStringHashKey, MacOSFamilyEntry> mOtherFamilyNames;    
+    nsDataHashtable< nsStringHashKey,
+                     RefPtr<MacOSFamilyEntry> > mOtherFamilyNames;
 
     // cached pref font lists
     // maps list of family names ==> array of family entries, one per lang group
-    nsDataHashtable<nsUint32HashKey, nsTArray<nsRefPtr<MacOSFamilyEntry> > > mPrefFonts;
+    nsDataHashtable<nsUint32HashKey,
+                    nsTArray<RefPtr<MacOSFamilyEntry> > > mPrefFonts;
 
     // when system-wide font lookup fails for a character, cache it to skip future searches
     gfxSparseBitSet mCodepointsWithNoFonts;
diff --git a/gfx/thebes/src/gfxQuartzFontCache.mm b/gfx/thebes/src/gfxQuartzFontCache.mm
--- a/gfx/thebes/src/gfxQuartzFontCache.mm
+++ b/gfx/thebes/src/gfxQuartzFontCache.mm
@@ -846,7 +846,7 @@ gfxQuartzFontCache::InitOtherFamilyNames
 }
                                                          
 PLDHashOperator PR_CALLBACK gfxQuartzFontCache::InitOtherFamilyNamesProc(nsStringHashKey::KeyType aKey,
-                                                         nsRefPtr<MacOSFamilyEntry>& aFamilyEntry,
+                                                         RefPtr<MacOSFamilyEntry>& aFamilyEntry,
                                                          void* userArg)
 {
     gfxQuartzFontCache *fc = (gfxQuartzFontCache*) userArg;
@@ -887,7 +887,6 @@ gfxQuartzFontCache::InitSingleFaceList()
             if (familyEntry) {
                 MacOSFontEntry *fontEntry = familyEntry->FindFont(singleFaceFonts[i]);
                 if (fontEntry) {
-                    PRBool found;
                     nsAutoString displayName, key;
                     
                     // use the display name the canonical name
@@ -896,7 +895,7 @@ gfxQuartzFontCache::InitSingleFaceList()
                     GenerateFontListKey(displayName, key);
 
                     // add only if doesn't exist already
-                    if (!(familyEntry = mFontFamilies.GetWeak(key, &found))) {
+                    if (!(familyEntry = mFontFamilies.Get(key, nsnull))) {
                         familyEntry = new SingleFaceFamily(displayName);
                         familyEntry->AddFontEntry(fontEntry);
                         mFontFamilies.Put(key, familyEntry);
@@ -919,13 +918,12 @@ gfxQuartzFontCache::PreloadNamesList()
     
     PRUint32 numFonts = preloadFonts.Length();
     for (PRUint32 i = 0; i < numFonts; i++) {
-        PRBool found;
         nsAutoString key;
         GenerateFontListKey(preloadFonts[i], key);
         
         // only search canonical names!
-        MacOSFamilyEntry *familyEntry = mFontFamilies.GetWeak(key, &found);
-        if (familyEntry) {
+        RefPtr<MacOSFamilyEntry> familyEntry;
+        if (mFontFamilies.Get(key, &familyEntry)) {
             AddOtherFamilyNameFunctor addOtherNames(this);
             familyEntry->ReadOtherFamilyNames(addOtherNames);
         }
@@ -939,8 +937,8 @@ gfxQuartzFontCache::EliminateDuplicateFa
     MacOSFamilyEntry *family = FindFamily(aFamilyName);
     if (!family) return;
 
-    nsTArray<nsRefPtr<MacOSFontEntry> >& fontlist = family->GetFontList();
-
+    nsTArray<RefPtr<MacOSFontEntry> >& fontlist = family->GetFontList();
+    
     PRUint32 i, bold, numFonts, italicIndex;
     MacOSFontEntry *italic, *nonitalic;
     PRUint32 boldtraits[2] = { 0, NSBoldFontMask };
@@ -1119,8 +1117,8 @@ struct FontListData {
 
 PLDHashOperator PR_CALLBACK
 gfxQuartzFontCache::HashEnumFuncForFamilies(nsStringHashKey::KeyType aKey,
-                                            nsRefPtr<MacOSFamilyEntry>& aFamilyEntry,
-                                            void *aUserArg)
+                                            RefPtr<MacOSFamilyEntry>& aFamilyEntry,
+                                            void* aUserArg)
 {
     FontListData *data = (FontListData*)aUserArg;
 
@@ -1207,8 +1205,8 @@ gfxQuartzFontCache::FindFontForChar(cons
 }
 
 PLDHashOperator PR_CALLBACK 
-gfxQuartzFontCache::FindFontForCharProc(nsStringHashKey::KeyType aKey, nsRefPtr<MacOSFamilyEntry>& aFamilyEntry,
-     void *userArg)
+gfxQuartzFontCache::FindFontForCharProc(nsStringHashKey::KeyType aKey, RefPtr<MacOSFamilyEntry>& aFamilyEntry,
+     void* userArg)
 {
     FontSearch *data = (FontSearch*)userArg;
 
@@ -1222,16 +1220,15 @@ gfxQuartzFontCache::FindFamily(const nsA
 {
     nsAutoString key;
     MacOSFamilyEntry *familyEntry;
-    PRBool found;
     GenerateFontListKey(aFamily, key);
 
     // lookup in canonical (i.e. English) family name list
-    if ((familyEntry = mFontFamilies.GetWeak(key, &found))) {
+    if (mFontFamilies.Get(key, &familyEntry)) {
         return familyEntry;
     }
 
     // lookup in other family names list (mostly localized names)
-    if ((familyEntry = mOtherFamilyNames.GetWeak(key, &found))) {
+    if (mOtherFamilyNames.Get(key, &familyEntry)) {
         return familyEntry;
     }
 
@@ -1240,7 +1237,7 @@ gfxQuartzFontCache::FindFamily(const nsA
     // since reading name table entries is expensive
     if (!mOtherFamilyNamesInitialized) {
         InitOtherFamilyNames();
-        if ((familyEntry = mOtherFamilyNames.GetWeak(key, &found))) {
+        if (mOtherFamilyNames.Get(key, &familyEntry)) {
             return familyEntry;
         }
     }
@@ -1272,13 +1269,13 @@ gfxQuartzFontCache::AppleWeightToCSSWeig
 }
 
 PRBool
-gfxQuartzFontCache::GetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<nsRefPtr<MacOSFamilyEntry> > *array)
+gfxQuartzFontCache::GetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<RefPtr<MacOSFamilyEntry> > *array)
 {
     return mPrefFonts.Get(PRUint32(aLangGroup), array);
 }
 
 void
-gfxQuartzFontCache::SetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<nsRefPtr<MacOSFamilyEntry> >& array)
+gfxQuartzFontCache::SetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<RefPtr<MacOSFamilyEntry> >& array)
 {
     mPrefFonts.Put(PRUint32(aLangGroup), array);
 }
@@ -1287,10 +1284,9 @@ gfxQuartzFontCache::AddOtherFamilyName(M
 gfxQuartzFontCache::AddOtherFamilyName(MacOSFamilyEntry *aFamilyEntry, nsAString& aOtherFamilyName)
 {
     nsAutoString key;
-    PRBool found;
     GenerateFontListKey(aOtherFamilyName, key);
 
-    if (!mOtherFamilyNames.GetWeak(key, &found)) {
+    if (!mOtherFamilyNames.Get(key, nsnull)) {
         mOtherFamilyNames.Put(key, aFamilyEntry);
         PR_LOG(gFontInfoLog, PR_LOG_DEBUG, ("(fontinit-otherfamily) canonical family: %s, other family: %s\n", 
                                             NS_ConvertUTF16toUTF8(aFamilyEntry->Name()).get(), 
diff --git a/gfx/thebes/src/gfxQuartzImageSurface.cpp b/gfx/thebes/src/gfxQuartzImageSurface.cpp
--- a/gfx/thebes/src/gfxQuartzImageSurface.cpp
+++ b/gfx/thebes/src/gfxQuartzImageSurface.cpp
@@ -58,20 +58,18 @@ gfxQuartzImageSurface::~gfxQuartzImageSu
 {
 }
 
-already_AddRefed<gfxImageSurface>
+AddRefed<gfxImageSurface>
 gfxQuartzImageSurface::GetImageSurface()
 {
     if (!mSurfaceValid)
-        return nsnull;
+        return AddRefed<gfxImageSurface>(nsnull);
 
     cairo_surface_t *isurf = cairo_quartz_image_surface_get_image (CairoSurface());
     if (!isurf) {
         NS_WARNING ("Couldn't obtain an image surface from a QuartzImageSurface?!");
-        return nsnull;
+        return AddRefed<gfxImageSurface>(nsnull);
     }
 
-    nsRefPtr<gfxASurface> asurf = gfxASurface::Wrap(isurf);
-    gfxImageSurface *imgsurf = (gfxImageSurface*) asurf.get();
-    NS_ADDREF(imgsurf);
-    return imgsurf;
+    return AddRefed<gfxImageSurface>(
+        static_cast<gfxImageSurface*>(gfxASurface::Wrap(isurf).get()));
 }
diff --git a/gfx/thebes/src/gfxQuartzNativeDrawing.cpp b/gfx/thebes/src/gfxQuartzNativeDrawing.cpp
--- a/gfx/thebes/src/gfxQuartzNativeDrawing.cpp
+++ b/gfx/thebes/src/gfxQuartzNativeDrawing.cpp
@@ -62,7 +62,7 @@ gfxQuartzNativeDrawing::BeginNativeDrawi
     NS_ASSERTION(!mQuartzSurface, "BeginNativeDrawing called when drawing already in progress");
 
     gfxPoint deviceOffset;
-    nsRefPtr<gfxASurface> surf = mContext->CurrentSurface(&deviceOffset.x, &deviceOffset.y);
+    RefPtr<gfxASurface> surf = mContext->CurrentSurface(&deviceOffset.x, &deviceOffset.y);
     if (!surf || surf->CairoStatus())
         return nsnull;
 
diff --git a/gfx/thebes/src/gfxWindowsFonts.cpp b/gfx/thebes/src/gfxWindowsFonts.cpp
--- a/gfx/thebes/src/gfxWindowsFonts.cpp
+++ b/gfx/thebes/src/gfxWindowsFonts.cpp
@@ -112,7 +112,7 @@ struct DCFromContext {
 struct DCFromContext {
     DCFromContext(gfxContext *aContext) {
         dc = NULL;
-        nsRefPtr<gfxASurface> aSurface = aContext->CurrentSurface();
+        RefPtr<gfxASurface> aSurface = aContext->CurrentSurface();
         NS_ASSERTION(aSurface, "DCFromContext: null surface");
         if (aSurface &&
             (aSurface->GetType() == gfxASurface::SurfaceTypeWin32 ||
@@ -743,7 +743,7 @@ gfxWindowsFont::SetupCairoFont(gfxContex
  * In either case, add a ref, append it to the aFonts array, and return it ---
  * except for OOM in which case we do nothing and return null.
  */
-already_AddRefed<gfxWindowsFont>
+AddRefed<gfxWindowsFont>
 gfxWindowsFont::GetOrMakeFont(FontEntry *aFontEntry, const gfxFontStyle *aStyle)
 {
     // because we know the FontEntry has the weight we really want, use it for matching
@@ -754,16 +754,14 @@ gfxWindowsFont::GetOrMakeFont(FontEntry 
     if (style.sizeAdjust == 0.0)
         style.size = ROUND(style.size);
 
-    nsRefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aFontEntry->GetName(), &style);
+    RefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aFontEntry->GetName(), &style);
     if (!font) {
         font = new gfxWindowsFont(aFontEntry->GetName(), &style, aFontEntry);
         if (!font)
-            return nsnull;
+            return AddRefed<gfxWindowsFont>(nsnull);
         gfxFontCache::GetCache()->AddNew(font);
     }
-    gfxFont *f = nsnull;
-    font.swap(f);
-    return static_cast<gfxWindowsFont *>(f);
+    return do_AddRef(static_cast<gfxWindowsFont*>(font.get()));
 }
 
 static PRBool
@@ -782,14 +780,14 @@ AddFontNameToArray(const nsAString& aNam
 }
 
 void
-gfxWindowsFontGroup::GroupFamilyListToArrayList(nsTArray<nsRefPtr<FontEntry> > *list)
+gfxWindowsFontGroup::GroupFamilyListToArrayList(nsTArray<RefPtr<FontEntry> > *list)
 {
     nsAutoTArray<nsString, 15> fonts;
     ForEachFont(AddFontNameToArray, &fonts);
 
     PRUint32 len = fonts.Length();
     for (PRUint32 i = 0; i < len; ++i) {
-        nsRefPtr<FontEntry> fe = gfxWindowsPlatform::GetPlatform()->FindFontEntry(fonts[i], mStyle);
+        RefPtr<FontEntry> fe = gfxWindowsPlatform::GetPlatform()->FindFontEntry(fonts[i], mStyle);
         list->AppendElement(fe);
     }
 }
@@ -797,7 +795,7 @@ void
 void
 gfxWindowsFontGroup::FamilyListToArrayList(const nsString& aFamilies,
                                            const nsCString& aLangGroup,
-                                           nsTArray<nsRefPtr<FontEntry> > *list)
+                                           nsTArray<RefPtr<FontEntry> > *list)
 {
     nsAutoTArray<nsString, 15> fonts;
     ForEachFont(aFamilies, aLangGroup, AddFontNameToArray, &fonts);
@@ -805,7 +803,7 @@ gfxWindowsFontGroup::FamilyListToArrayLi
     PRUint32 len = fonts.Length();
     for (PRUint32 i = 0; i < len; ++i) {
         const nsString& str = fonts[i];
-        nsRefPtr<FontEntry> fe = gfxWindowsPlatform::GetPlatform()->FindFontEntry(str, mStyle);
+        RefPtr<FontEntry> fe = gfxWindowsPlatform::GetPlatform()->FindFontEntry(str, mStyle);
         list->AppendElement(fe);
     }
 }
@@ -885,7 +883,7 @@ gfxWindowsFontGroup::GetFontAt(PRInt32 i
 gfxWindowsFontGroup::GetFontAt(PRInt32 i)
 {
     if (!mFonts[i]) {
-        nsRefPtr<gfxWindowsFont> font =
+        RefPtr<gfxWindowsFont> font =
             gfxWindowsFont::GetOrMakeFont(mFontEntries[i], &mStyle);
         mFonts[i] = font;
     }
@@ -1068,7 +1066,7 @@ gfxWindowsFontGroup::InitTextRunGDI(gfxC
 gfxWindowsFontGroup::InitTextRunGDI(gfxContext *aContext, gfxTextRun *aRun,
                                     const char *aString, PRUint32 aLength)
 {
-    nsRefPtr<gfxWindowsFont> font = GetFontAt(0);
+    RefPtr<gfxWindowsFont> font = GetFontAt(0);
     DCFromContext dc(aContext);
     if (SetupDCFont(dc, font)) {
         nsAutoTArray<WCHAR,500> glyphArray;
@@ -1092,7 +1090,7 @@ gfxWindowsFontGroup::InitTextRunGDI(gfxC
 gfxWindowsFontGroup::InitTextRunGDI(gfxContext *aContext, gfxTextRun *aRun,
                                     const PRUnichar *aString, PRUint32 aLength)
 {
-    nsRefPtr<gfxWindowsFont> font = GetFontAt(0);
+    RefPtr<gfxWindowsFont> font = GetFontAt(0);
     DCFromContext dc(aContext);
     if (SetupDCFont(dc, font)) {
         nsAutoTArray<WCHAR,500> glyphArray;
@@ -1608,12 +1606,12 @@ public:
     struct TextRange {
         TextRange(PRUint32 aStart,  PRUint32 aEnd) : start(aStart), end(aEnd) { }
         PRUint32 Length() const { return end - start; }
-        nsRefPtr<gfxWindowsFont> font;
+        RefPtr<gfxWindowsFont> font;
         PRUint32 start, end;
     };
 
     void SetRange(PRUint32 i) {
-        nsRefPtr<gfxWindowsFont> font;
+        RefPtr<gfxWindowsFont> font;
         if (mRanges[i].font)
             font = mRanges[i].font;
         else
@@ -1633,7 +1631,7 @@ public:
             if (ch > 0xFFFF)
                 return PR_FALSE;
 
-            nsRefPtr<gfxWindowsFont> font =
+            RefPtr<gfxWindowsFont> font =
                 gfxWindowsFont::GetOrMakeFont(aFontEntry, mGroup->GetStyle());
             if (!font->IsValid())
                 return PR_FALSE;
@@ -1671,10 +1669,10 @@ public:
         return PR_FALSE;
     }
 
-    inline already_AddRefed<gfxWindowsFont>
-    WhichFontSupportsChar(const nsTArray<nsRefPtr<FontEntry> >& fonts, PRUint32 ch) {
+    inline AddRefed<gfxWindowsFont>
+    WhichFontSupportsChar(const nsTArray<RefPtr<FontEntry> >& fonts, PRUint32 ch) {
         for (PRUint32 i = 0; i < fonts.Length(); i++) {
-            nsRefPtr<FontEntry> fe = fonts[i];
+            RefPtr<FontEntry> fe = fonts[i];
             if (fe->mSymbolFont && !mGroup->GetStyle()->familyNameQuirks)
                 continue;
             if (HasCharacter(fe, ch)) {
@@ -1695,10 +1693,10 @@ public:
                 ch == 0x2060);
     }
 
-    inline already_AddRefed<gfxWindowsFont>
+    inline AddRefed<gfxWindowsFont>
     FindFontForChar(PRUint32 ch, PRUint32 prevCh, PRUint32 nextCh,
                     gfxWindowsFont *aFont) {
-        nsRefPtr<gfxWindowsFont> selectedFont;
+        RefPtr<gfxWindowsFont> selectedFont;
 
         // if this character or the next one is a joiner use the
         // same font as the previous range if we can
@@ -1734,7 +1732,7 @@ public:
                 if (langGroup) {
                     PR_LOG(gFontLog, PR_LOG_DEBUG, (" - Trying to find fonts for: %s (%s)", langGroup, gScriptToText[primaryId].value));
 
-                    nsAutoTArray<nsRefPtr<FontEntry>, 5> fonts;
+                    nsAutoTArray<RefPtr<FontEntry>, 5> fonts;
                     this->GetPrefFonts(langGroup, fonts);
                     selectedFont = WhichFontSupportsChar(fonts, ch);
                 }
@@ -1746,7 +1744,7 @@ public:
                     if (PR_LOG_TEST(gFontLog, PR_LOG_DEBUG))
                         PR_LOG(gFontLog, PR_LOG_DEBUG, (" - Trying to find fonts for: CJK"));
 
-                    nsAutoTArray<nsRefPtr<FontEntry>, 15> fonts;
+                    nsAutoTArray<RefPtr<FontEntry>, 15> fonts;
                     this->GetCJKPrefFonts(fonts);
                     selectedFont = WhichFontSupportsChar(fonts, ch);
                 } else {
@@ -1754,7 +1752,7 @@ public:
                     if (langGroup) {
                         PR_LOG(gFontLog, PR_LOG_DEBUG, (" - Trying to find fonts for: %s", langGroup));
 
-                        nsAutoTArray<nsRefPtr<FontEntry>, 5> fonts;
+                        nsAutoTArray<RefPtr<FontEntry>, 5> fonts;
                         this->GetPrefFonts(langGroup, fonts);
                         selectedFont = WhichFontSupportsChar(fonts, ch);
                     }
@@ -1770,7 +1768,7 @@ public:
         if (!selectedFont) {
             PR_LOG(gFontLog, PR_LOG_DEBUG, (" - Looking for best match"));
 
-            nsRefPtr<gfxWindowsFont> refFont = mGroup->GetFontAt(0);
+            RefPtr<gfxWindowsFont> refFont = mGroup->GetFontAt(0);
             gfxWindowsPlatform *platform = gfxWindowsPlatform::GetPlatform();
             selectedFont = platform->FindFontForChar(ch, refFont);
         }
@@ -1800,7 +1798,7 @@ public:
                 if ((i+2 < mItemLength) && NS_IS_HIGH_SURROGATE(nextCh) && NS_IS_LOW_SURROGATE(mItemString[i+2]))
                     nextCh = SURROGATE_TO_UCS4(nextCh, mItemString[i+2]);
             }
-            nsRefPtr<gfxWindowsFont> font =
+            RefPtr<gfxWindowsFont> font =
                 FindFontForChar(ch,
                                 prevCh,
                                 nextCh,
@@ -1848,10 +1846,10 @@ private:
     }
 
     // this function appends to the array passed in.
-    void GetPrefFonts(const char *aLangGroup, nsTArray<nsRefPtr<FontEntry> >& array) {
+    void GetPrefFonts(const char *aLangGroup, nsTArray<RefPtr<FontEntry> >& array) {
         NS_ASSERTION(aLangGroup, "aLangGroup is null");
         gfxWindowsPlatform *platform = gfxWindowsPlatform::GetPlatform();
-        nsAutoTArray<nsRefPtr<FontEntry>, 5> fonts;
+        nsAutoTArray<RefPtr<FontEntry>, 5> fonts;
         /* this lookup has to depend on weight and style */
         nsCAutoString key(aLangGroup);
         key.Append("-");
@@ -1873,7 +1871,7 @@ private:
     }
 
     // this function assigns to the array passed in.
-    void GetCJKPrefFonts(nsTArray<nsRefPtr<FontEntry> >& array) {
+    void GetCJKPrefFonts(nsTArray<RefPtr<FontEntry> >& array) {
         gfxWindowsPlatform *platform = gfxWindowsPlatform::GetPlatform();
 
         nsCAutoString key("x-internal-cjk-");
@@ -1960,7 +1958,7 @@ private:
     }
 
 private:
-    nsRefPtr<gfxContext> mContext;
+    RefPtr<gfxContext> mContext;
     HDC mDC;
 
     SCRIPT_ITEM *mScriptItem;
@@ -1992,7 +1990,7 @@ private:
     int mMaxGlyphs;
     int mNumGlyphs;
 
-    nsRefPtr<gfxWindowsFont> mCurrentFont;
+    RefPtr<gfxWindowsFont> mCurrentFont;
 
     PRPackedBool mFontSelected;
 
@@ -2152,7 +2150,7 @@ public:
     }
 
 private:
-    nsRefPtr<gfxContext> mContext;
+    RefPtr<gfxContext> mContext;
     HDC mDC;
     const PRUnichar *mString;
     const PRUint32 mLength;
diff --git a/gfx/thebes/src/gfxWindowsNativeDrawing.cpp b/gfx/thebes/src/gfxWindowsNativeDrawing.cpp
--- a/gfx/thebes/src/gfxWindowsNativeDrawing.cpp
+++ b/gfx/thebes/src/gfxWindowsNativeDrawing.cpp
@@ -68,7 +68,7 @@ gfxWindowsNativeDrawing::BeginNativeDraw
 gfxWindowsNativeDrawing::BeginNativeDrawing()
 {
     if (mRenderState == RENDER_STATE_INIT) {
-        nsRefPtr<gfxASurface> surf = mContext->CurrentSurface(&mDeviceOffset.x, &mDeviceOffset.y);
+        RefPtr<gfxASurface> surf = mContext->CurrentSurface(&mDeviceOffset.x, &mDeviceOffset.y);
         if (!surf || surf->CairoStatus())
             return nsnull;
 
@@ -258,9 +258,9 @@ gfxWindowsNativeDrawing::PaintToContext(
         // nothing to do, it already went to the context
         mRenderState = RENDER_STATE_DONE;
     } else if (mRenderState == RENDER_STATE_ALPHA_RECOVERY_WHITE_DONE) {
-        nsRefPtr<gfxImageSurface> black = mBlackSurface->GetImageSurface();
-        nsRefPtr<gfxImageSurface> white = mWhiteSurface->GetImageSurface();
-        nsRefPtr<gfxImageSurface> alphaSurface =
+        RefPtr<gfxImageSurface> black = mBlackSurface->GetImageSurface();
+        RefPtr<gfxImageSurface> white = mWhiteSurface->GetImageSurface();
+        RefPtr<gfxImageSurface> alphaSurface =
             gfxAlphaRecovery::RecoverAlpha(black, white, mTempSurfaceSize);
 
         mContext->Save();
@@ -268,7 +268,7 @@ gfxWindowsNativeDrawing::PaintToContext(
         mContext->NewPath();
         mContext->Rectangle(gfxRect(gfxPoint(0.0, 0.0), mNativeRect.size));
 
-        nsRefPtr<gfxPattern> pat = new gfxPattern(alphaSurface);
+        RefPtr<gfxPattern> pat = new gfxPattern(alphaSurface);
 
         gfxMatrix m;
         m.Scale(mScale.width, mScale.height);
diff --git a/gfx/thebes/src/gfxWindowsPlatform.cpp b/gfx/thebes/src/gfxWindowsPlatform.cpp
--- a/gfx/thebes/src/gfxWindowsPlatform.cpp
+++ b/gfx/thebes/src/gfxWindowsPlatform.cpp
@@ -102,13 +102,12 @@ gfxWindowsPlatform::~gfxWindowsPlatform(
 {
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 gfxWindowsPlatform::CreateOffscreenSurface(const gfxIntSize& size,
                                            gfxASurface::gfxImageFormat imageFormat)
 {
     gfxASurface *surf = new gfxWindowsSurface(size, imageFormat);
-    NS_IF_ADDREF(surf);
-    return surf;
+    return do_AddRef(surf);
 }
 
 int CALLBACK 
@@ -128,7 +127,7 @@ gfxWindowsPlatform::FontEnumProc(const E
     nsAutoString name(logFont.lfFaceName);
     BuildKeyNameFromFontName(name);
 
-    nsRefPtr<FontFamily> ff;
+    RefPtr<FontFamily> ff;
     if (!ht->Get(name, &ff)) {
         ff = new FontFamily(nsDependentString(logFont.lfFaceName));
         ht->Put(name, ff);
@@ -150,7 +149,7 @@ struct FontListData {
 
 PLDHashOperator PR_CALLBACK
 gfxWindowsPlatform::HashEnumFunc(nsStringHashKey::KeyType aKey,
-                                 nsRefPtr<FontFamily>& aFontFamily,
+                                 RefPtr<FontFamily>& aFontFamily,
                                  void* userArg)
 {
     FontListData *data = (FontListData*)userArg;
@@ -257,7 +256,7 @@ gfxWindowsPlatform::UpdateFontList()
         BuildKeyNameFromFontName(substituteName);
         RemoveCharsetFromFontSubstitute(actualFontName);
         BuildKeyNameFromFontName(actualFontName);
-        nsRefPtr<FontFamily> ff;
+        RefPtr<FontFamily> ff;
         if (!actualFontName.IsEmpty() && mFonts.Get(actualFontName, &ff))
             mFontSubstitutes.Put(substituteName, ff);
         else
@@ -356,7 +355,7 @@ gfxWindowsPlatform::ResolveFontName(cons
     nsAutoString keyName(aFontName);
     BuildKeyNameFromFontName(keyName);
 
-    nsRefPtr<FontFamily> ff;
+    RefPtr<FontFamily> ff;
     if (mFonts.Get(keyName, &ff) ||
         mFontSubstitutes.Get(keyName, &ff) ||
         mFontAliases.Get(keyName, &ff)) {
@@ -407,7 +406,7 @@ gfxWindowsPlatform::FontResolveProc(cons
     nsAutoString name(logFont.lfFaceName);
 
     // Save the alias name to cache
-    nsRefPtr<FontFamily> ff;
+    RefPtr<FontFamily> ff;
     nsAutoString keyName(name);
     BuildKeyNameFromFontName(keyName);
     if (!rData->mCaller->mFonts.Get(keyName, &ff)) {
@@ -432,14 +431,14 @@ struct FontSearch {
         ch(aCh), fontToMatch(aFont), matchRank(-1) {
     }
     PRUint32 ch;
-    nsRefPtr<gfxWindowsFont> fontToMatch;
+    RefPtr<gfxWindowsFont> fontToMatch;
     PRInt32 matchRank;
-    nsRefPtr<FontEntry> bestMatch;
+    RefPtr<FontEntry> bestMatch;
 };
 
 PLDHashOperator PR_CALLBACK
 gfxWindowsPlatform::FindFontForCharProc(nsStringHashKey::KeyType aKey,
-                                        nsRefPtr<FontFamily>& aFontFamily,
+                                        RefPtr<FontFamily>& aFontFamily,
                                         void* userArg)
 {
     FontSearch *data = (FontSearch*)userArg;
@@ -528,7 +527,7 @@ gfxWindowsPlatform::FindFontFamily(const
     nsAutoString name(aName);
     BuildKeyNameFromFontName(name);
 
-    nsRefPtr<FontFamily> ff;
+    RefPtr<FontFamily> ff;
     if (!mFonts.Get(name, &ff) &&
         !mFontSubstitutes.Get(name, &ff) &&
         !mFontAliases.Get(name, &ff)) {
@@ -569,13 +568,13 @@ gfxWindowsPlatform::GetPlatformCMSOutput
 }
 
 PRBool
-gfxWindowsPlatform::GetPrefFontEntries(const nsCString& aKey, nsTArray<nsRefPtr<FontEntry> > *array)
+gfxWindowsPlatform::GetPrefFontEntries(const nsCString& aKey, nsTArray<RefPtr<FontEntry> > *array)
 {
     return mPrefFonts.Get(aKey, array);
 }
 
 void
-gfxWindowsPlatform::SetPrefFontEntries(const nsCString& aKey, nsTArray<nsRefPtr<FontEntry> >& array)
+gfxWindowsPlatform::SetPrefFontEntries(const nsCString& aKey, nsTArray<RefPtr<FontEntry> >& array)
 {
     mPrefFonts.Put(aKey, array);
 }
diff --git a/gfx/thebes/src/gfxWindowsSurface.cpp b/gfx/thebes/src/gfxWindowsSurface.cpp
--- a/gfx/thebes/src/gfxWindowsSurface.cpp
+++ b/gfx/thebes/src/gfxWindowsSurface.cpp
@@ -122,50 +122,46 @@ gfxWindowsSurface::~gfxWindowsSurface()
     }
 }
 
-already_AddRefed<gfxImageSurface>
+AddRefed<gfxImageSurface>
 gfxWindowsSurface::GetImageSurface()
 {
     if (!mSurfaceValid) {
         NS_WARNING ("GetImageSurface on an invalid (null) surface; who's calling this without checking for surface errors?");
-        return nsnull;
+        return AddRefed<gfxImageSurface>(nsnull);
     }
 
     NS_ASSERTION(CairoSurface() != nsnull, "CairoSurface() shouldn't be nsnull when mSurfaceValid is TRUE!");
 
     if (mForPrinting)
-        return nsnull;
+        return AddRefed<gfxImageSurface>(nsnull);
 
     cairo_surface_t *isurf = cairo_win32_surface_get_image(CairoSurface());
     if (!isurf)
-        return nsnull;
+        return AddRefed<gfxImageSurface>(nsnull);
 
-    nsRefPtr<gfxASurface> asurf = gfxASurface::Wrap(isurf);
-    gfxImageSurface *imgsurf = (gfxImageSurface*) asurf.get();
-    NS_ADDREF(imgsurf);
-    return imgsurf;
+    RefPtr<gfxASurface> asurf = gfxASurface::Wrap(isurf);
+    return do_AddRef(static_cast<gfxImageSurface*>(asurf.get()));
 }
 
-already_AddRefed<gfxWindowsSurface>
+AddRefed<gfxWindowsSurface>
 gfxWindowsSurface::OptimizeToDDB(HDC dc, const gfxIntSize& size, gfxImageFormat format)
 {
     if (mForPrinting)
-        return nsnull;
+        return AddRefed<gfxWindowsSurface>(nsnull);
 
     if (format != ImageFormatRGB24)
-        return nsnull;
+        return AddRefed<gfxWindowsSurface>(nsnull);
 
-    nsRefPtr<gfxWindowsSurface> wsurf = new gfxWindowsSurface(dc, size, format);
+    RefPtr<gfxWindowsSurface> wsurf = new gfxWindowsSurface(dc, size, format);
     if (wsurf->CairoStatus() != 0)
-        return nsnull;
+        return AddRefed<gfxWindowsSurface>(nsnull);
 
     gfxContext tmpCtx(wsurf);
     tmpCtx.SetOperator(gfxContext::OPERATOR_SOURCE);
     tmpCtx.SetSource(this);
     tmpCtx.Paint();
 
-    gfxWindowsSurface *raw = (gfxWindowsSurface*) (wsurf.get());
-    NS_ADDREF(raw);
-    return raw;
+    return do_AddRef(wsurf);
 }
 
 static char*
diff --git a/gfx/thebes/src/gfxXlibNativeRenderer.cpp b/gfx/thebes/src/gfxXlibNativeRenderer.cpp
--- a/gfx/thebes/src/gfxXlibNativeRenderer.cpp
+++ b/gfx/thebes/src/gfxXlibNativeRenderer.cpp
@@ -39,6 +39,8 @@
 #include "gfxContext.h"
 
 #include "cairo-xlib-utils.h"
+
+using namespace mozilla;
 
 #ifdef MOZ_WIDGET_GTK2
 #include <gdk/gdkscreen.h>
diff --git a/gfx/thebes/test/gfxFontSelectionTest.cpp b/gfx/thebes/test/gfxFontSelectionTest.cpp
--- a/gfx/thebes/test/gfxFontSelectionTest.cpp
+++ b/gfx/thebes/test/gfxFontSelectionTest.cpp
@@ -58,6 +58,8 @@
 #ifdef MOZ_WIDGET_GTK2
 #include "gtk/gtk.h"
 #endif
+
+using namespace mozilla;
 
 enum {
     S_UTF8 = 0,
@@ -223,17 +225,16 @@ struct TestEntry {
 
 nsTArray<TestEntry> testList;
 
-already_AddRefed<gfxContext>
+AddRefed<gfxContext>
 MakeContext ()
 {
     const int size = 200;
 
-    nsRefPtr<gfxASurface> surface;
+    RefPtr<gfxASurface> surface;
 
     surface = gfxPlatform::GetPlatform()->CreateOffscreenSurface(gfxIntSize(size, size), gfxASurface::ImageFormatRGB24);
-    gfxContext *ctx = new gfxContext(surface);
-    NS_IF_ADDREF(ctx);
-    return ctx;
+
+    return do_AddRef(new gfxContext(surface));
 }
 
 TestEntry*
@@ -286,7 +287,7 @@ DumpTestExpect (TestEntry *test) {
 
 PRBool
 RunTest (TestEntry *test, gfxContext *ctx) {
-    nsRefPtr<gfxFontGroup> fontGroup;
+    RefPtr<gfxFontGroup> fontGroup;
 
     fontGroup = gfxPlatform::GetPlatform()->CreateFontGroup(NS_ConvertUTF8toUTF16(test->utf8FamilyString), &test->fontStyle);
 
@@ -378,7 +379,7 @@ main (int argc, char **argv) {
     // set up the tests
     SetupTests();
 
-    nsRefPtr<gfxContext> context = MakeContext();
+    RefPtr<gfxContext> context = MakeContext();
 
     for (uint test = 0;
          test < testList.Length();
diff --git a/gfx/thebes/test/gfxSurfaceRefCountTest.cpp b/gfx/thebes/test/gfxSurfaceRefCountTest.cpp
--- a/gfx/thebes/test/gfxSurfaceRefCountTest.cpp
+++ b/gfx/thebes/test/gfxSurfaceRefCountTest.cpp
@@ -1,3 +1,5 @@
+/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
+
 #include <stdio.h>
 
 #include "gfxASurface.h"
@@ -5,10 +7,13 @@
 
 #include "cairo.h"
 
+using namespace mozilla;
+
 int
 GetASurfaceRefCount(gfxASurface *s) {
-    NS_ADDREF(s);
-    return s->Release();
+    s->AddReference();
+    s->ReleaseReference();
+    return s->GetRefCount();
 }
 
 int
@@ -42,7 +47,7 @@ TestNewSurface () {
     int failures = 0;
     int destroyed = 0;
 
-    nsRefPtr<gfxASurface> s = new gfxImageSurface (gfxIntSize(10, 10), gfxASurface::ImageFormatARGB32);
+    RefPtr<gfxASurface> s = new gfxImageSurface (gfxIntSize(10, 10), gfxASurface::ImageFormatARGB32);
     cairo_surface_t *cs = s->CairoSurface();
 
     cairo_surface_set_user_data (cs, &destruction_key, &destroyed, SurfaceDestroyNotifier);
@@ -96,7 +101,7 @@ TestExistingSurface () {
     failures += CheckInt (cairo_surface_get_reference_count(cs), 1);
     failures += CheckInt (destroyed, 0);
 
-    nsRefPtr<gfxASurface> s = gfxASurface::Wrap(cs);
+    RefPtr<gfxASurface> s = gfxASurface::Wrap(cs);
 
     failures += CheckInt (GetASurfaceRefCount(s.get()), 2);
 
diff --git a/gfx/thebes/test/gfxTextRunPerfTest.cpp b/gfx/thebes/test/gfxTextRunPerfTest.cpp
--- a/gfx/thebes/test/gfxTextRunPerfTest.cpp
+++ b/gfx/thebes/test/gfxTextRunPerfTest.cpp
@@ -60,6 +60,8 @@
 #include "gtk/gtk.h"
 #endif
 
+using namespace mozilla;
+
 struct TestEntry {
   const char* mFamilies;
   const char* mString;
@@ -70,20 +72,19 @@ TestEntry testList[] = {
 { nsnull, nsnull } // terminator
 };
 
-already_AddRefed<gfxContext>
+AddRefed<gfxContext>
 MakeContext ()
 {
     const int size = 200;
 
-    nsRefPtr<gfxASurface> surface;
+    RefPtr<gfxASurface> surface;
 
     surface = gfxPlatform::GetPlatform()->CreateOffscreenSurface(gfxIntSize(size, size), gfxASurface::ImageFormatRGB24);
-    gfxContext *ctx = new gfxContext(surface);
-    NS_IF_ADDREF(ctx);
-    return ctx;
+
+    return do_AddRef(new gfxContext(surface));
 }
 
-nsRefPtr<gfxFontGroup> fontGroup;
+RefPtr<gfxFontGroup> fontGroup;
 const char* lastFamilies = nsnull;
 
 void
@@ -154,7 +155,7 @@ main (int argc, char **argv) {
     fflush (stderr);
     fflush (stdout);
 
-    nsRefPtr<gfxContext> context = MakeContext();
+    RefPtr<gfxContext> context = MakeContext();
 
     // Start timing
     PRIntervalTime start = PR_IntervalNow();
diff --git a/gfx/thebes/test/gfxWordCacheTest.cpp b/gfx/thebes/test/gfxWordCacheTest.cpp
--- a/gfx/thebes/test/gfxWordCacheTest.cpp
+++ b/gfx/thebes/test/gfxWordCacheTest.cpp
@@ -62,6 +62,8 @@
 #include "gtk/gtk.h"
 #endif
 
+using namespace mozilla;
+
 class FrameTextRunCache;
 
 static FrameTextRunCache *gTextRuns = nsnull;
@@ -116,17 +118,16 @@ MakeTextRun(const PRUnichar *aText, PRUi
    return textRun.forget();
 }
 
-already_AddRefed<gfxContext>
+AddRefed<gfxContext>
 MakeContext ()
 {
    const int size = 200;
 
-   nsRefPtr<gfxASurface> surface;
+   RefPtr<gfxASurface> surface;
 
    surface = gfxPlatform::GetPlatform()->CreateOffscreenSurface(gfxIntSize(size, size), gfxASurface::ImageFormatRGB24);
-   gfxContext *ctx = new gfxContext(surface);
-   NS_IF_ADDREF(ctx);
-   return ctx;
+
+   return do_AddRef(new gfxContext(surface));
 }
 
 int
@@ -153,7 +154,7 @@ main (int argc, char **argv) {
 
    gTextRuns = new FrameTextRunCache();
 
-   nsRefPtr<gfxContext> ctx = MakeContext();
+   RefPtr<gfxContext> ctx = MakeContext();
    {
        gfxFontStyle style (FONT_STYLE_NORMAL,
                            139,
@@ -162,7 +163,7 @@ main (int argc, char **argv) {
                            0.0,
                            PR_FALSE, PR_FALSE);
 
-       nsRefPtr<gfxFontGroup> fontGroup =
+       RefPtr<gfxFontGroup> fontGroup =
            gfxPlatform::GetPlatform()->CreateFontGroup(NS_LITERAL_STRING("Geneva, MS Sans Serif, Helvetica,serif"), &style);
 
        gfxTextRunFactory::Parameters params = {
diff --git a/layout/base/nsCSSRendering.cpp b/layout/base/nsCSSRendering.cpp
--- a/layout/base/nsCSSRendering.cpp
+++ b/layout/base/nsCSSRendering.cpp
@@ -75,6 +75,8 @@
 
 #include "gfxContext.h"
 
+using namespace mozilla;
+
 #define BORDER_FULL    0        //entire side
 #define BORDER_INSIDE  1        //inside half
 #define BORDER_OUTSIDE 2        //outside half
@@ -3369,7 +3371,7 @@ nsCSSRendering::PaintBoxShadow(nsPresCon
     shadowRectPlusBlur.RoundOut();
 
     gfxContext* renderContext = aRenderingContext.ThebesContext();
-    nsRefPtr<gfxContext> shadowContext;
+    RefPtr<gfxContext> shadowContext;
     nsContextBoxBlur blurringArea;
 
     // shadowRect has already been converted to device pixels, pass 1 as the appunits/pixel value
@@ -4595,7 +4597,7 @@ nsCSSRendering::PaintDecorationLine(gfxC
   PRBool contextIsSaved = PR_FALSE;
 
   gfxFloat oldLineWidth;
-  nsRefPtr<gfxPattern> oldPattern;
+  RefPtr<gfxPattern> oldPattern;
 
   switch (aStyle) {
     case NS_STYLE_BORDER_STYLE_SOLID:
diff --git a/layout/base/nsCSSRendering.h b/layout/base/nsCSSRendering.h
--- a/layout/base/nsCSSRendering.h
+++ b/layout/base/nsCSSRendering.h
@@ -390,8 +390,8 @@ protected:
                        PRUint32 aTopLobe,
                        PRUint32 aBottomLobe);
 
-  nsRefPtr<gfxContext> mContext;
-  nsRefPtr<gfxImageSurface> mImageSurface;
+  mozilla::RefPtr<gfxContext> mContext;
+  mozilla::RefPtr<gfxImageSurface> mImageSurface;
   gfxContext* mDestinationCtx;
 
   // Contrary to what is passed as parameters, these are in device pixels
diff --git a/layout/base/nsDisplayList.cpp b/layout/base/nsDisplayList.cpp
--- a/layout/base/nsDisplayList.cpp
+++ b/layout/base/nsDisplayList.cpp
@@ -50,6 +50,8 @@
 #include "nsRegion.h"
 #include "nsFrameManager.h"
 #include "gfxContext.h"
+
+using namespace mozilla;
 
 nsDisplayListBuilder::nsDisplayListBuilder(nsIFrame* aReferenceFrame,
     PRBool aIsForEvents, PRBool aBuildCaret)
diff --git a/layout/base/nsIPresShell.h b/layout/base/nsIPresShell.h
--- a/layout/base/nsIPresShell.h
+++ b/layout/base/nsIPresShell.h
@@ -64,6 +64,7 @@
 #include "mozFlushType.h"
 #include "nsWeakReference.h"
 #include <stdio.h> // for FILE definition
+#include "gfxASurface.h"
 
 class nsIAtom;
 class nsIContent;
@@ -746,10 +747,10 @@ public:
    * edge of the presshell area. The aPoint, aScreenRect and aSurface
    * arguments function in a similar manner as RenderSelection.
    */
-  virtual already_AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
-                                                   nsIRegion* aRegion,
-                                                   nsPoint& aPoint,
-                                                   nsRect* aScreenRect) = 0;
+  virtual mozilla::AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
+                                                    nsIRegion* aRegion,
+                                                    nsPoint& aPoint,
+                                                    nsRect* aScreenRect) = 0;
 
   /*
    * Renders a selection to a surface and returns it. This method is primarily
@@ -766,9 +767,9 @@ public:
    * the original. When scaling does not occur, the mouse point isn't used
    * as the position can be determined from the displayed frames.
    */
-  virtual already_AddRefed<gfxASurface> RenderSelection(nsISelection* aSelection,
-                                                        nsPoint& aPoint,
-                                                        nsRect* aScreenRect) = 0;
+  virtual mozilla::AddRefed<gfxASurface> RenderSelection(nsISelection* aSelection,
+                                                         nsPoint& aPoint,
+                                                         nsRect* aScreenRect) = 0;
 
   void AddWeakFrame(nsWeakFrame* aWeakFrame);
   void RemoveWeakFrame(nsWeakFrame* aWeakFrame);
diff --git a/layout/base/nsLayoutUtils.cpp b/layout/base/nsLayoutUtils.cpp
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -78,6 +78,8 @@
 #include "nsSVGForeignObjectFrame.h"
 #include "nsSVGOuterSVGFrame.h"
 #endif
+
+using namespace mozilla;
 
 /**
  * A namespace class for static layout utilities.
diff --git a/layout/base/nsPresShell.cpp b/layout/base/nsPresShell.cpp
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -207,6 +207,8 @@ static NS_DEFINE_CID(kCSSStyleSheetCID, 
 static NS_DEFINE_CID(kCSSStyleSheetCID, NS_CSS_STYLESHEET_CID);
 static NS_DEFINE_IID(kRangeCID,     NS_RANGE_CID);
 
+using namespace mozilla;
+
 PRBool nsIPresShell::gIsAccessibilityActive = PR_FALSE;
 
 // convert a color value to a string, in the CSS format #RRGGBB
@@ -887,14 +889,14 @@ public:
                             nscolor aBackgroundColor,
                             gfxContext* aThebesContext);
 
-  virtual already_AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
-                                                   nsIRegion* aRegion,
-                                                   nsPoint& aPoint,
-                                                   nsRect* aScreenRect);
-
-  virtual already_AddRefed<gfxASurface> RenderSelection(nsISelection* aSelection,
-                                                        nsPoint& aPoint,
-                                                        nsRect* aScreenRect);
+  virtual AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
+                                                     nsIRegion* aRegion,
+                                                     nsPoint& aPoint,
+                                                     nsRect* aScreenRect);
+
+  virtual AddRefed<gfxASurface> RenderSelection(nsISelection* aSelection,
+                                                          nsPoint& aPoint,
+                                                          nsRect* aScreenRect);
 
   //nsIViewObserver interface
 
@@ -1094,7 +1096,7 @@ protected:
    * aScreenRect - [out] set to the area of the screen the painted area should
    *               be displayed at
    */
-  already_AddRefed<gfxASurface>
+  AddRefed<gfxASurface>
   PaintRangePaintInfo(nsTArray<nsAutoPtr<RangePaintInfo> >* aItems,
                       nsISelection* aSelection,
                       nsIRegion* aRegion,
@@ -5187,7 +5189,7 @@ PresShell::CreateRangePaintInfo(nsIDOMRa
   return info;
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 PresShell::PaintRangePaintInfo(nsTArray<nsAutoPtr<RangePaintInfo> >* aItems,
                                nsISelection* aSelection,
                                nsIRegion* aRegion,
@@ -5197,7 +5199,7 @@ PresShell::PaintRangePaintInfo(nsTArray<
 {
   nsPresContext* pc = GetPresContext();
   if (!pc || aArea.width == 0 || aArea.height == 0)
-    return nsnull;
+    return AddRefed<gfxASurface>(nsnull);
 
   nsIDeviceContext* deviceContext = pc->DeviceContext();
 
@@ -5247,7 +5249,7 @@ PresShell::PaintRangePaintInfo(nsTArray<
                         gfxImageSurface::ImageFormatARGB32);
   if (!surface || surface->CairoStatus()) {
     delete surface;
-    return nsnull;
+    return AddRefed<gfxASurface>(nsnull);
   }
 
   // clear the image
@@ -5300,11 +5302,11 @@ PresShell::PaintRangePaintInfo(nsTArray<
   // restore the old selection display state
   frameSelection->SetDisplaySelection(oldDisplaySelection);
 
-  NS_ADDREF(surface);
-  return surface;
-}
-
-already_AddRefed<gfxASurface>
+  surface->AddReference();
+  return AddRefed<gfxASurface>(surface);
+}
+
+AddRefed<gfxASurface>
 PresShell::RenderNode(nsIDOMNode* aNode,
                       nsIRegion* aRegion,
                       nsPoint& aPoint,
@@ -5322,7 +5324,7 @@ PresShell::RenderNode(nsIDOMNode* aNode,
   RangePaintInfo* info = CreateRangePaintInfo(range, area);
   if (info && !rangeItems.AppendElement(info)) {
     delete info;
-    return nsnull;
+    return AddRefed<gfxASurface>(nsnull);
   }
 
   if (aRegion) {
@@ -5337,7 +5339,7 @@ PresShell::RenderNode(nsIDOMNode* aNode,
     
     nsPresContext* pc = GetPresContext();
     if (!pc)
-      return nsnull;
+      return AddRefed<gfxASurface>(nsnull);
 
     // move the region so that it is offset from the topleft corner of the surface
     aRegion->Offset(-rrectPixels.x + (rrectPixels.x - pc->AppUnitsToDevPixels(area.x)),
@@ -5348,7 +5350,7 @@ PresShell::RenderNode(nsIDOMNode* aNode,
                              aScreenRect);
 }
 
-already_AddRefed<gfxASurface>
+AddRefed<gfxASurface>
 PresShell::RenderSelection(nsISelection* aSelection,
                            nsPoint& aPoint,
                            nsRect* aScreenRect)
@@ -5373,7 +5375,7 @@ PresShell::RenderSelection(nsISelection*
     RangePaintInfo* info = CreateRangePaintInfo(range, area);
     if (info && !rangeItems.AppendElement(info)) {
       delete info;
-      return nsnull;
+      return AddRefed<gfxASurface>(nsnull);
     }
   }
 
@@ -7047,20 +7049,20 @@ DumpToPNG(nsIPresShell* shell, nsAString
   nsRect r(0, 0, shell->GetPresContext()->DevPixelsToAppUnits(width),
                  shell->GetPresContext()->DevPixelsToAppUnits(height));
 
-  nsRefPtr<gfxImageSurface> imgSurface =
+  RefPtr<gfxImageSurface> imgSurface =
      new gfxImageSurface(gfxIntSize(width, height),
                          gfxImageSurface::ImageFormatARGB32);
   NS_ENSURE_TRUE(imgSurface, NS_ERROR_OUT_OF_MEMORY);
 
-  nsRefPtr<gfxContext> imgContext = new gfxContext(imgSurface);
-
-  nsRefPtr<gfxASurface> surface = 
+  RefPtr<gfxContext> imgContext = new gfxContext(imgSurface);
+
+  RefPtr<gfxASurface> surface = 
     gfxPlatform::GetPlatform()->
     CreateOffscreenSurface(gfxIntSize(width, height),
       gfxASurface::ImageFormatARGB32);
   NS_ENSURE_TRUE(surface, NS_ERROR_OUT_OF_MEMORY);
 
-  nsRefPtr<gfxContext> context = new gfxContext(surface);
+  RefPtr<gfxContext> context = new gfxContext(surface);
   NS_ENSURE_TRUE(context, NS_ERROR_OUT_OF_MEMORY);
 
   nsresult rv = shell->RenderDocument(r, PR_FALSE, PR_FALSE,
diff --git a/layout/generic/nsBlockFrame.cpp b/layout/generic/nsBlockFrame.cpp
--- a/layout/generic/nsBlockFrame.cpp
+++ b/layout/generic/nsBlockFrame.cpp
@@ -101,6 +101,8 @@ static const int MIN_LINES_NEEDING_CURSO
 #ifdef DEBUG
 #include "nsPrintfCString.h"
 #include "nsBlockDebugFlags.h"
+
+using namespace mozilla;
 
 PRBool nsBlockFrame::gLamePaintMetrics;
 PRBool nsBlockFrame::gLameReflowMetrics;
diff --git a/layout/generic/nsFrame.cpp b/layout/generic/nsFrame.cpp
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -121,6 +121,8 @@
 #include "nsDisplayList.h"
 
 #include "gfxContext.h"
+
+using namespace mozilla;
 
 static NS_DEFINE_CID(kLookAndFeelCID,  NS_LOOKANDFEEL_CID);
 static NS_DEFINE_CID(kWidgetCID, NS_CHILD_CID);
diff --git a/layout/generic/nsHTMLContainerFrame.cpp b/layout/generic/nsHTMLContainerFrame.cpp
--- a/layout/generic/nsHTMLContainerFrame.cpp
+++ b/layout/generic/nsHTMLContainerFrame.cpp
@@ -72,6 +72,8 @@
 #include "nsLineBox.h"
 #include "nsDisplayList.h"
 #include "nsCSSRendering.h"
+
+using namespace mozilla;
 
 class nsDisplayTextDecoration : public nsDisplayItem {
 public:
diff --git a/layout/generic/nsObjectFrame.cpp b/layout/generic/nsObjectFrame.cpp
--- a/layout/generic/nsObjectFrame.cpp
+++ b/layout/generic/nsObjectFrame.cpp
@@ -1436,7 +1436,7 @@ nsObjectFrame::PaintPlugin(nsIRenderingC
 
       /* Set the device offsets as appropriate, for whatever our current group offsets might be */
       gfxFloat xoff, yoff;
-      nsRefPtr<gfxASurface> surf = ctx->CurrentSurface(&xoff, &yoff);
+      RefPtr<gfxASurface> surf = ctx->CurrentSurface(&xoff, &yoff);
 
       if (surf->CairoStatus() != 0) {
         NS_WARNING("Plugin is being asked to render to a surface that's in error!");
diff --git a/layout/generic/nsTextFrameThebes.cpp b/layout/generic/nsTextFrameThebes.cpp
--- a/layout/generic/nsTextFrameThebes.cpp
+++ b/layout/generic/nsTextFrameThebes.cpp
@@ -118,6 +118,8 @@
 #include "gfxTextRunWordCache.h"
 #include "gfxImageSurface.h"
 
+using namespace mozilla;
+
 #ifdef NS_DEBUG
 #undef NOISY_BLINK
 #undef NOISY_REFLOW
@@ -1290,7 +1292,7 @@ GetFontGroupForFrame(nsIFrame* aFrame,
   return fm->GetThebesFontGroup();
 }
 
-static already_AddRefed<gfxContext>
+static AddRefed<gfxContext>
 GetReferenceRenderingContext(nsTextFrame* aTextFrame, nsIRenderingContext* aRC)
 {
   nsCOMPtr<nsIRenderingContext> tmp = aRC;
@@ -1298,12 +1300,11 @@ GetReferenceRenderingContext(nsTextFrame
     nsresult rv = aTextFrame->PresContext()->PresShell()->
       CreateRenderingContext(aTextFrame, getter_AddRefs(tmp));
     if (NS_FAILED(rv))
-      return nsnull;
+      return AddRefed<gfxContext>(nsnull);
   }
 
   gfxContext* ctx = tmp->ThebesContext();
-  NS_ADDREF(ctx);
-  return ctx;
+  return do_AddRef(ctx);
 }
 
 /**
@@ -1313,7 +1314,7 @@ static gfxTextRun*
 static gfxTextRun*
 GetHyphenTextRun(gfxTextRun* aTextRun, gfxContext* aContext, nsTextFrame* aTextFrame)
 {
-  nsRefPtr<gfxContext> ctx = aContext;
+  RefPtr<gfxContext> ctx = aContext;
   if (!ctx) {
     ctx = GetReferenceRenderingContext(aTextFrame, nsnull);
   }
@@ -1785,7 +1786,7 @@ nsTextFrame::EnsureTextRun(gfxContext* a
       gTextRuns->MarkUsed(mTextRun);
     }
   } else {
-    nsRefPtr<gfxContext> ctx = aReferenceContext;
+    RefPtr<gfxContext> ctx = aReferenceContext;
     if (!ctx) {
       ctx = GetReferenceRenderingContext(this, nsnull);
     }
diff --git a/layout/generic/nsTextRunTransformations.cpp b/layout/generic/nsTextRunTransformations.cpp
--- a/layout/generic/nsTextRunTransformations.cpp
+++ b/layout/generic/nsTextRunTransformations.cpp
@@ -45,6 +45,8 @@
 #include "nsStyleContext.h"
 #include "gfxContext.h"
 #include "nsContentUtils.h"
+
+using namespace mozilla;
 
 #define SZLIG 0x00DF
 
@@ -288,7 +290,7 @@ nsFontVariantTextRunFactory::RebuildText
   gfxFontGroup* fontGroup = aTextRun->GetFontGroup();
   gfxFontStyle fontStyle = *fontGroup->GetStyle();
   fontStyle.size *= 0.8;
-  nsRefPtr<gfxFontGroup> smallFont = fontGroup->Copy(&fontStyle);
+  RefPtr<gfxFontGroup> smallFont = fontGroup->Copy(&fontStyle);
   if (!smallFont)
     return;
 
diff --git a/layout/mathml/base/src/nsMathMLChar.cpp b/layout/mathml/base/src/nsMathMLChar.cpp
--- a/layout/mathml/base/src/nsMathMLChar.cpp
+++ b/layout/mathml/base/src/nsMathMLChar.cpp
@@ -74,6 +74,8 @@
 
 #include "nsMathMLOperators.h"
 #include "nsMathMLChar.h"
+
+using namespace mozilla;
 
 //#define SHOW_BORDERS 1
 //#define NOISY_SEARCH 1
@@ -2226,7 +2228,7 @@ nsMathMLChar::PaintVertically(nsPresCont
   }
   nscoord dx = aRect.x;
   nscoord offset[3], start[3], end[3];
-  nsRefPtr<gfxContext> ctx = aRenderingContext.ThebesContext();
+  RefPtr<gfxContext> ctx = aRenderingContext.ThebesContext();
   for (i = 0; i <= bottom; ++i) {
     ch = chdata[i];
     const nsBoundingMetrics& bm = bmdata[i];
@@ -2456,7 +2458,7 @@ nsMathMLChar::PaintHorizontally(nsPresCo
   }
   nscoord dy = aRect.y + mBoundingMetrics.ascent;
   nscoord offset[3], start[3], end[3];
-  nsRefPtr<gfxContext> ctx = aRenderingContext.ThebesContext();
+  RefPtr<gfxContext> ctx = aRenderingContext.ThebesContext();
   for (i = 0; i <= right; ++i) {
     ch = chdata[i];
     const nsBoundingMetrics& bm = bmdata[i];
diff --git a/layout/svg/base/src/nsSVGFilterFrame.cpp b/layout/svg/base/src/nsSVGFilterFrame.cpp
--- a/layout/svg/base/src/nsSVGFilterFrame.cpp
+++ b/layout/svg/base/src/nsSVGFilterFrame.cpp
@@ -47,6 +47,8 @@
 #include "gfxASurface.h"
 #include "gfxContext.h"
 #include "gfxImageSurface.h"
+
+using namespace mozilla;
 
 nsIFrame*
 NS_NewSVGFilterFrame(nsIPresShell* aPresShell, nsIContent* aContent, nsStyleContext* aContext)
@@ -444,7 +446,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
   if (!analysis.GetSourceColorAlphaNeeded().IsEmpty() ||
       !analysis.GetSourceAlphaNeeded().IsEmpty()) {
     // paint the target geometry
-    nsRefPtr<gfxImageSurface> tmpSurface = instance.GetImage();
+    RefPtr<gfxImageSurface> tmpSurface = instance.GetImage();
     if (!tmpSurface) {
       FilterFailCleanup(aContext, aTarget);
       return NS_OK;
@@ -458,7 +460,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
     aTarget->PaintSVG(&tmpState, nsnull);
 
     if (!analysis.GetSourceAlphaNeeded().IsEmpty()) {
-      nsRefPtr<gfxImageSurface> alpha = instance.GetImage();
+      RefPtr<gfxImageSurface> alpha = instance.GetImage();
       if (!alpha) {
         FilterFailCleanup(aContext, aTarget);
         return NS_OK;
@@ -492,7 +494,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
     // but we have to because all filter primitives currently need to
     // call AcquireSourceImage and find a source image, even if they don't
     // use it!
-    nsRefPtr<gfxImageSurface> tmpSurface = instance.GetImage();
+    RefPtr<gfxImageSurface> tmpSurface = instance.GetImage();
     if (!tmpSurface) {
       FilterFailCleanup(aContext, aTarget);
       return NS_OK;
@@ -515,7 +517,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
   }
 
   nsRect filterRect;
-  nsRefPtr<gfxImageSurface> filterSurface;
+  RefPtr<gfxImageSurface> filterSurface;
 
   instance.LookupImage(NS_LITERAL_STRING(""),
                        getter_AddRefs(filterSurface), &filterRect, colorModel);
@@ -732,15 +734,15 @@ nsSVGFilterInstance::GetFilterSubregion(
 #endif
 }
 
-already_AddRefed<gfxImageSurface>
+AddRefed<gfxImageSurface>
 nsSVGFilterInstance::GetImage()
 {
-  nsRefPtr<gfxImageSurface> surface =
+  RefPtr<gfxImageSurface> surface =
     new gfxImageSurface(gfxIntSize(mSurfaceRect.width, mSurfaceRect.height),
                         gfxASurface::ImageFormatARGB32);
 
   if (!surface || surface->CairoStatus()) {
-    return nsnull;
+    return AddRefed<gfxImageSurface>(nsnull);
   }
 
   surface->SetDeviceOffset(gfxPoint(-mSurfaceRect.x, -mSurfaceRect.y));
@@ -750,9 +752,7 @@ nsSVGFilterInstance::GetImage()
   ctx.SetOperator(gfxContext::OPERATOR_CLEAR);
   ctx.Paint();
 
-  gfxImageSurface *retval = nsnull;
-  surface.swap(retval);
-  return retval;
+  return surface.forget();
 }
 
 void
@@ -773,7 +773,7 @@ nsSVGFilterInstance::LookupImage(const n
   }
 
   *aImage = entry->mImage;
-  NS_ADDREF(*aImage);
+  entry->mImage->AddReference();
   *aRegion = entry->mRegion;
 
   if (aRequiredColorModel == entry->mColorModel)
diff --git a/layout/svg/base/src/nsSVGFilterInstance.h b/layout/svg/base/src/nsSVGFilterInstance.h
--- a/layout/svg/base/src/nsSVGFilterInstance.h
+++ b/layout/svg/base/src/nsSVGFilterInstance.h
@@ -79,7 +79,7 @@ public:
   // device offsets so that its origin is positioned at mSurfaceRect.TopLeft()
   // when using cairo to draw into the surface). The surface is cleared
   // to transparent black.
-  already_AddRefed<gfxImageSurface> GetImage();
+  mozilla::AddRefed<gfxImageSurface> GetImage();
 
   void LookupImage(const nsAString &aName,
                    gfxImageSurface **aImage,
@@ -134,7 +134,7 @@ private:
       mImage(aImage), mRegion(aRegion), mColorModel(aColorModel) {
     }
 
-    nsRefPtr<gfxImageSurface> mImage;
+    mozilla::RefPtr<gfxImageSurface> mImage;
     nsRect mRegion;
     ColorModel mColorModel;
   };
diff --git a/layout/svg/base/src/nsSVGGlyphFrame.cpp b/layout/svg/base/src/nsSVGGlyphFrame.cpp
--- a/layout/svg/base/src/nsSVGGlyphFrame.cpp
+++ b/layout/svg/base/src/nsSVGGlyphFrame.cpp
@@ -54,6 +54,8 @@
 #include "gfxMatrix.h"
 #include "gfxPlatform.h"
 #include "gfxTextRunWordCache.h"
+
+using namespace mozilla;
 
 struct CharacterPosition {
   gfxPoint pos;
@@ -426,7 +428,7 @@ NS_IMETHODIMP
 NS_IMETHODIMP
 nsSVGGlyphFrame::UpdateCoveredRegion()
 {
-  nsRefPtr<gfxContext> tmpCtx = MakeTmpCtx();
+  RefPtr<gfxContext> tmpCtx = MakeTmpCtx();
   SetupGlobalTransform(tmpCtx);
   CharacterIterator iter(this, PR_TRUE);
   iter.SetInitialMatrix(tmpCtx);
@@ -555,7 +557,7 @@ nsSVGGlyphFrame::GetBBox(nsIDOMSVGRect *
 {
   *_retval = nsnull;
 
-  nsRefPtr<gfxContext> tmpCtx = MakeTmpCtx();
+  RefPtr<gfxContext> tmpCtx = MakeTmpCtx();
   SetupGlobalTransform(tmpCtx);
   CharacterIterator iter(this, PR_TRUE);
   iter.SetInitialMatrix(tmpCtx);
@@ -625,7 +627,7 @@ nsSVGGlyphFrame::GetCharacterPositions(n
   if (!textPath)
     return PR_TRUE;
 
-  nsRefPtr<gfxFlattenedPath> data = textPath->GetFlattenedPath();
+  RefPtr<gfxFlattenedPath> data = textPath->GetFlattenedPath();
 
   /* textPath frame, but invalid target */
   if (!data)
@@ -843,7 +845,7 @@ nsSVGGlyphFrame::GetEndPositionOfChar(PR
   if (!iter.AdvanceToCharacter(charnum))
     return NS_ERROR_DOM_INDEX_SIZE_ERR;
 
-  nsRefPtr<gfxContext> tmpCtx = MakeTmpCtx();
+  RefPtr<gfxContext> tmpCtx = MakeTmpCtx();
   iter.SetupForMetrics(tmpCtx);
   tmpCtx->MoveTo(gfxPoint(mTextRun->GetAdvanceWidth(charnum, 1, nsnull), 0));
   tmpCtx->IdentityMatrix();
@@ -862,7 +864,7 @@ nsSVGGlyphFrame::GetExtentOfChar(PRUint3
   gfxTextRun::Metrics metrics =
     mTextRun->MeasureText(charnum, 1, PR_FALSE, nsnull, nsnull);
 
-  nsRefPtr<gfxContext> tmpCtx = MakeTmpCtx();
+  RefPtr<gfxContext> tmpCtx = MakeTmpCtx();
   iter.SetupForMetrics(tmpCtx);
   tmpCtx->Rectangle(metrics.mBoundingBox);
   tmpCtx->IdentityMatrix();
@@ -1080,7 +1082,7 @@ nsSVGGlyphFrame::GetCharNumAtPosition(ns
   point->GetX(&xPos);
   point->GetY(&yPos);
 
-  nsRefPtr<gfxContext> tmpCtx = MakeTmpCtx();
+  RefPtr<gfxContext> tmpCtx = MakeTmpCtx();
   CharacterIterator iter(this, PR_FALSE);
 
   PRInt32 i;
@@ -1150,7 +1152,7 @@ PRBool
 PRBool
 nsSVGGlyphFrame::ContainsPoint(float x, float y)
 {
-  nsRefPtr<gfxContext> tmpCtx = MakeTmpCtx();
+  RefPtr<gfxContext> tmpCtx = MakeTmpCtx();
   SetupGlobalTransform(tmpCtx);
   CharacterIterator iter(this, PR_TRUE);
   iter.SetInitialMatrix(tmpCtx);
@@ -1254,7 +1256,7 @@ nsSVGGlyphFrame::EnsureTextRun(float *aD
                            font.sizeAdjust, font.systemFont,
                            font.familyNameQuirks);
 
-    nsRefPtr<gfxFontGroup> fontGroup =
+    RefPtr<gfxFontGroup> fontGroup =
       gfxPlatform::GetPlatform()->CreateFontGroup(font.name, &fontStyle);
 
     PRUint32 flags = gfxTextRunFactory::TEXT_NEED_BOUNDING_BOX |
@@ -1263,7 +1265,7 @@ nsSVGGlyphFrame::EnsureTextRun(float *aD
     // XXX We should use a better surface here! But then we'd have to
     // change things so we can ensure we always have the "right" sort of
     // surface available, by creating the textrun only at the right times
-    nsRefPtr<gfxContext> tmpCtx = MakeTmpCtx();
+    RefPtr<gfxContext> tmpCtx = MakeTmpCtx();
     tmpCtx->SetMatrix(m);
 
     // Use only the word cache here. We don't want to cache the textrun
diff --git a/layout/svg/base/src/nsSVGGradientFrame.cpp b/layout/svg/base/src/nsSVGGradientFrame.cpp
--- a/layout/svg/base/src/nsSVGGradientFrame.cpp
+++ b/layout/svg/base/src/nsSVGGradientFrame.cpp
@@ -48,6 +48,8 @@
 #include "gfxContext.h"
 #include "nsIDOMSVGRect.h"
 #include "gfxPattern.h"
+
+using namespace mozilla;
 
 //----------------------------------------------------------------------
 // Implementation
@@ -344,7 +346,7 @@ nsSVGGradientFrame::SetupPaintServer(gfx
 
   patternMatrix.Invert();
 
-  nsRefPtr<gfxPattern> gradient = CreateGradient();
+  RefPtr<gfxPattern> gradient = CreateGradient();
   if (!gradient || gradient->CairoStatus())
     return PR_FALSE;
 
@@ -597,7 +599,7 @@ nsSVGLinearGradientFrame::GradientLookup
     GetAnimValue(static_cast<nsSVGSVGElement*>(nsnull));
 }
 
-already_AddRefed<gfxPattern>
+AddRefed<gfxPattern>
 nsSVGLinearGradientFrame::CreateGradient()
 {
   float x1, y1, x2, y2;
@@ -607,9 +609,7 @@ nsSVGLinearGradientFrame::CreateGradient
   x2 = GradientLookupAttribute(nsGkAtoms::x2, nsSVGLinearGradientElement::X2);
   y2 = GradientLookupAttribute(nsGkAtoms::y2, nsSVGLinearGradientElement::Y2);
 
-  gfxPattern *pattern = new gfxPattern(x1, y1, x2, y2);
-  NS_IF_ADDREF(pattern);
-  return pattern;
+  return do_AddRef(new gfxPattern(x1, y1, x2, y2));
 }
 
 // -------------------------------------------------------------------------
@@ -679,7 +679,7 @@ nsSVGRadialGradientFrame::GradientLookup
     GetAnimValue(static_cast<nsSVGSVGElement*>(nsnull));
 }
 
-already_AddRefed<gfxPattern>
+AddRefed<gfxPattern>
 nsSVGRadialGradientFrame::CreateGradient()
 {
   float cx, cy, r, fx, fy;
@@ -719,9 +719,7 @@ nsSVGRadialGradientFrame::CreateGradient
     }
   }
 
-  gfxPattern *pattern = new gfxPattern(fx, fy, 0, cx, cy, r);
-  NS_IF_ADDREF(pattern);
-  return pattern;
+  return do_AddRef(new gfxPattern(fx, fy, 0, cx, cy, r));
 }
 
 // -------------------------------------------------------------------------
diff --git a/layout/svg/base/src/nsSVGGradientFrame.h b/layout/svg/base/src/nsSVGGradientFrame.h
--- a/layout/svg/base/src/nsSVGGradientFrame.h
+++ b/layout/svg/base/src/nsSVGGradientFrame.h
@@ -133,7 +133,7 @@ private:
   gfxMatrix GetGradientTransform(nsSVGGeometryFrame *aSource);
 
 protected:
-  virtual already_AddRefed<gfxPattern> CreateGradient() = 0;
+  virtual mozilla::AddRefed<gfxPattern> CreateGradient() = 0;
 
   // Use these inline methods instead of GetGradientWithAttr(..., aGradType)
   nsIContent* GetLinearGradientWithAttr(nsIAtom *aAttrName)
@@ -221,7 +221,7 @@ public:
 
 protected:
   float GradientLookupAttribute(nsIAtom *aAtomName, PRUint16 aEnumName);
-  virtual already_AddRefed<gfxPattern> CreateGradient();
+  virtual mozilla::AddRefed<gfxPattern> CreateGradient();
 };
 
 // -------------------------------------------------------------------------
@@ -259,7 +259,7 @@ protected:
 protected:
   float GradientLookupAttribute(nsIAtom *aAtomName, PRUint16 aEnumName,
                                 nsIContent *aElement = nsnull);
-  virtual already_AddRefed<gfxPattern> CreateGradient();
+  virtual mozilla::AddRefed<gfxPattern> CreateGradient();
 };
 
 #endif // __NS_SVGGRADIENTFRAME_H__
diff --git a/layout/svg/base/src/nsSVGImageFrame.cpp b/layout/svg/base/src/nsSVGImageFrame.cpp
--- a/layout/svg/base/src/nsSVGImageFrame.cpp
+++ b/layout/svg/base/src/nsSVGImageFrame.cpp
@@ -48,6 +48,8 @@
 #include "gfxContext.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIImage.h"
+
+using namespace mozilla;
 
 class nsSVGImageFrame;
 
@@ -252,7 +254,7 @@ nsSVGImageFrame::PaintSVG(nsSVGRenderSta
   if (mImageContainer)
     mImageContainer->GetCurrentFrame(getter_AddRefs(currentFrame));
 
-  nsRefPtr<gfxPattern> thebesPattern = nsnull;
+  RefPtr<gfxPattern> thebesPattern = nsnull;
   if (currentFrame) {
     nsCOMPtr<nsIImage> img(do_GetInterface(currentFrame));
 
diff --git a/layout/svg/base/src/nsSVGMaskFrame.cpp b/layout/svg/base/src/nsSVGMaskFrame.cpp
--- a/layout/svg/base/src/nsSVGMaskFrame.cpp
+++ b/layout/svg/base/src/nsSVGMaskFrame.cpp
@@ -43,6 +43,8 @@
 #include "nsIDOMSVGRect.h"
 #include "gfxImageSurface.h"
 
+using namespace mozilla;
+
 //----------------------------------------------------------------------
 // Implementation
 
@@ -72,7 +74,7 @@ NS_GetSVGMaskElement(nsIURI *aURI, nsICo
   return nsnull;
 }
 
-already_AddRefed<gfxPattern>
+AddRefed<gfxPattern>
 nsSVGMaskFrame::ComputeMaskAlpha(nsSVGRenderState *aContext,
                                  nsISVGChildFrame* aParent,
                                  nsIDOMSVGMatrix* aMatrix,
@@ -83,7 +85,7 @@ nsSVGMaskFrame::ComputeMaskAlpha(nsSVGRe
   // has a mask reference loop.
   if (mInUse) {
     NS_WARNING("Mask loop detected!");
-    return nsnull;
+    return AddRefed<gfxPattern>(nsnull);
   }
   AutoMaskReferencer maskRef(this);
 
@@ -123,7 +125,7 @@ nsSVGMaskFrame::ComputeMaskAlpha(nsSVGRe
                                 nsISVGChildFrame::TRANSFORM_CHANGED);
 
       if (!bbox)
-        return nsnull;
+        return AddRefed<gfxPattern>(nsnull);
 
 #ifdef DEBUG_tor
       bbox->GetX(&x);
@@ -165,13 +167,13 @@ nsSVGMaskFrame::ComputeMaskAlpha(nsSVGRe
 
   gfx->Restore();
 
-  nsRefPtr<gfxPattern> pattern = gfx->PopGroup();
+  RefPtr<gfxPattern> pattern = gfx->PopGroup();
   if (!pattern || pattern->CairoStatus())
-    return nsnull;
+    return AddRefed<gfxPattern>(nsnull);
 
-  nsRefPtr<gfxASurface> surface = pattern->GetSurface();
+  RefPtr<gfxASurface> surface = pattern->GetSurface();
   if (!surface || surface->CairoStatus())
-    return nsnull;
+    return AddRefed<gfxPattern>(nsnull);
 
   surface->SetDeviceOffset(gfxPoint(0,0));
 
@@ -191,15 +193,15 @@ nsSVGMaskFrame::ComputeMaskAlpha(nsSVGRe
 
   // 0 disables mask, < 0 is an error
   if (surfaceSize.width <= 0 || surfaceSize.height <= 0)
-    return nsnull;
+    return AddRefed<gfxPattern>(nsnull);
 
   if (resultOverflows)
-    return nsnull;
+    return AddRefed<gfxPattern>(nsnull);
 
-  nsRefPtr<gfxImageSurface> image =
+  RefPtr<gfxImageSurface> image =
     new gfxImageSurface(surfaceSize, gfxASurface::ImageFormatARGB32);
   if (!image || image->CairoStatus())
-    return nsnull;
+    return AddRefed<gfxPattern>(nsnull);
 
   gfxContext transferCtx(image);
   transferCtx.SetOperator(gfxContext::OPERATOR_SOURCE);
@@ -231,9 +233,8 @@ nsSVGMaskFrame::ComputeMaskAlpha(nsSVGRe
   gfxPattern *retval = new gfxPattern(image);
   if (retval) {
     retval->SetMatrix(gfxMatrix().Translate(-clipExtents.pos));
-    NS_ADDREF(retval);
   }
-  return retval;
+  return do_AddRef(retval);
 }
 
 nsIAtom *
diff --git a/layout/svg/base/src/nsSVGMaskFrame.h b/layout/svg/base/src/nsSVGMaskFrame.h
--- a/layout/svg/base/src/nsSVGMaskFrame.h
+++ b/layout/svg/base/src/nsSVGMaskFrame.h
@@ -56,10 +56,10 @@ protected:
 
 public:
   // nsSVGMaskFrame method:
-  already_AddRefed<gfxPattern> ComputeMaskAlpha(nsSVGRenderState *aContext,
-                                                nsISVGChildFrame* aParent,
-                                                nsIDOMSVGMatrix* aMatrix,
-                                                float aOpacity = 1.0f);
+  mozilla::AddRefed<gfxPattern> ComputeMaskAlpha(nsSVGRenderState *aContext,
+                                                 nsISVGChildFrame* aParent,
+                                                 nsIDOMSVGMatrix* aMatrix,
+                                                 float aOpacity = 1.0f);
 
   /**
    * Get the "type" of the frame
diff --git a/layout/svg/base/src/nsSVGPatternFrame.cpp b/layout/svg/base/src/nsSVGPatternFrame.cpp
--- a/layout/svg/base/src/nsSVGPatternFrame.cpp
+++ b/layout/svg/base/src/nsSVGPatternFrame.cpp
@@ -55,6 +55,8 @@
 #include "gfxContext.h"
 #include "gfxPlatform.h"
 #include "gfxPattern.h"
+
+using namespace mozilla;
 
 #ifdef DEBUG_scooter
 static void printCTM(char *msg, gfxMatrix aCTM);
@@ -315,7 +317,7 @@ nsSVGPatternFrame::PaintPattern(gfxASurf
   printf("Creating %dX%d surface\n", int(surfaceSize.width), int(surfaceSize.height));
 #endif
 
-  nsRefPtr<gfxASurface> tmpSurface =
+  RefPtr<gfxASurface> tmpSurface =
     gfxPlatform::GetPlatform()->CreateOffscreenSurface(surfaceSize,
                                                        gfxASurface::ImageFormatARGB32);
   if (!tmpSurface || tmpSurface->CairoStatus())
@@ -354,7 +356,7 @@ nsSVGPatternFrame::PaintPattern(gfxASurf
   }
 
   // caller now owns the surface
-  tmpSurface.swap(*surface);
+  *surface = do_AddRef(tmpSurface).get();
   return NS_OK;
 }
 
@@ -843,7 +845,7 @@ nsSVGPatternFrame::SetupPaintServer(gfxC
   gfxMatrix matrix = aContext->CurrentMatrix();
 
   // Paint it!
-  nsRefPtr<gfxASurface> surface;
+  RefPtr<gfxASurface> surface;
   gfxMatrix pMatrix;
   aContext->IdentityMatrix();
   nsresult rv = PaintPattern(getter_AddRefs(surface), &pMatrix,
@@ -860,7 +862,7 @@ nsSVGPatternFrame::SetupPaintServer(gfxC
 
   pMatrix.Invert();
 
-  nsRefPtr<gfxPattern> pattern = new gfxPattern(surface);
+  RefPtr<gfxPattern> pattern = new gfxPattern(surface);
 
   if (!pattern || pattern->CairoStatus())
     return PR_FALSE;
diff --git a/layout/svg/base/src/nsSVGTextPathFrame.cpp b/layout/svg/base/src/nsSVGTextPathFrame.cpp
--- a/layout/svg/base/src/nsSVGTextPathFrame.cpp
+++ b/layout/svg/base/src/nsSVGTextPathFrame.cpp
@@ -46,6 +46,7 @@
 #include "nsSVGPathElement.h"
 #include "nsSVGTextPathElement.h"
 
+using namespace mozilla;
 
 NS_IMPL_ISUPPORTS1(nsSVGPathListener, nsIMutationObserver)
 
@@ -169,14 +170,17 @@ nsSVGTextPathFrame::GetPathFrame()
   return path;
 }
 
-already_AddRefed<gfxFlattenedPath>
+AddRefed<gfxFlattenedPath>
 nsSVGTextPathFrame::GetFlattenedPath()
 {
   nsIFrame *path = GetPathFrame();
-  return path ? GetFlattenedPath(path) : nsnull;
+  if (path)
+    return GetFlattenedPath(path);
+
+  return AddRefed<gfxFlattenedPath>(nsnull);
 }
  
-already_AddRefed<gfxFlattenedPath>
+AddRefed<gfxFlattenedPath>
 nsSVGTextPathFrame::GetFlattenedPath(nsIFrame *path)
 {
   NS_PRECONDITION(path, "Unexpected null path");
@@ -203,7 +207,7 @@ nsSVGTextPathFrame::GetStartOffset()
     return 0.0;
 
   if (length->IsPercentage()) {
-    nsRefPtr<gfxFlattenedPath> data = GetFlattenedPath();
+    RefPtr<gfxFlattenedPath> data = GetFlattenedPath();
     return data ? (val * data->GetLength() / 100.0) : 0.0;
   } else {
     return val * GetPathScale();
@@ -223,7 +227,7 @@ nsSVGTextPathFrame::GetPathScale()
   if (pl == 0.0f)
     return 1.0;
 
-  nsRefPtr<gfxFlattenedPath> data = GetFlattenedPath(pathFrame);
+  RefPtr<gfxFlattenedPath> data = GetFlattenedPath(pathFrame);
   return data ? data->GetLength() / pl : 1.0; 
 }
 
diff --git a/layout/svg/base/src/nsSVGTextPathFrame.h b/layout/svg/base/src/nsSVGTextPathFrame.h
--- a/layout/svg/base/src/nsSVGTextPathFrame.h
+++ b/layout/svg/base/src/nsSVGTextPathFrame.h
@@ -96,7 +96,7 @@ public:
 #endif
 
   // nsSVGTextPathFrame methods:
-  already_AddRefed<gfxFlattenedPath> GetFlattenedPath();
+  mozilla::AddRefed<gfxFlattenedPath> GetFlattenedPath();
   nsIFrame *GetPathFrame();
 
   gfxFloat GetStartOffset();
@@ -109,7 +109,7 @@ protected:
   NS_IMETHOD_(already_AddRefed<nsIDOMSVGLengthList>) GetDy();
 
 private:
-  already_AddRefed<gfxFlattenedPath> GetFlattenedPath(nsIFrame *path);
+  mozilla::AddRefed<gfxFlattenedPath> GetFlattenedPath(nsIFrame *path);
 
   nsCOMPtr<nsIDOMSVGAnimatedString> mHref;
   nsRefPtr<nsSVGPathListener> mPathListener;
diff --git a/layout/svg/base/src/nsSVGUtils.cpp b/layout/svg/base/src/nsSVGUtils.cpp
--- a/layout/svg/base/src/nsSVGUtils.cpp
+++ b/layout/svg/base/src/nsSVGUtils.cpp
@@ -82,6 +82,8 @@
 #include "nsSVGForeignObjectFrame.h"
 #include "nsIFontMetrics.h"
 #include "nsIDOMSVGUnitTypes.h"
+
+using namespace mozilla;
 
 static PRBool AddEffectProperties(nsIFrame *aFrame);
 
@@ -1390,11 +1392,12 @@ nsSVGUtils::PaintChildWithEffects(nsSVGR
 
   gfx->PopGroupToSource();
 
-  nsRefPtr<gfxPattern> maskSurface =
-    maskFrame ? maskFrame->ComputeMaskAlpha(aContext, svgChildFrame,
-                                            matrix, opacity) : nsnull;
+  RefPtr<gfxPattern> maskSurface;
+  if (maskFrame)
+    maskSurface = maskFrame->ComputeMaskAlpha(aContext, svgChildFrame,
+                                              matrix, opacity);
 
-  nsRefPtr<gfxPattern> clipMaskSurface;
+  RefPtr<gfxPattern> clipMaskSurface;
   if (clipPathFrame && !isTrivialClip) {
     gfx->PushGroup(gfxASurface::CONTENT_COLOR_ALPHA);
 
@@ -1580,13 +1583,13 @@ nsSVGUtils::GetThebesComputationalSurfac
 nsSVGUtils::GetThebesComputationalSurface()
 {
   if (!mThebesComputationalSurface) {
-    nsRefPtr<gfxImageSurface> surface =
+    RefPtr<gfxImageSurface> surface =
       new gfxImageSurface(gfxIntSize(1, 1), gfxASurface::ImageFormatARGB32);
     NS_ASSERTION(surface && !surface->CairoStatus(),
                  "Could not create offscreen surface");
     mThebesComputationalSurface = surface;
     // we want to keep this surface around
-    NS_IF_ADDREF(mThebesComputationalSurface);
+    mThebesComputationalSurface->AddReference();
   }
 
   return mThebesComputationalSurface;
diff --git a/layout/xul/base/src/nsTextBoxFrame.cpp b/layout/xul/base/src/nsTextBoxFrame.cpp
--- a/layout/xul/base/src/nsTextBoxFrame.cpp
+++ b/layout/xul/base/src/nsTextBoxFrame.cpp
@@ -76,6 +76,8 @@
 #include "nsBidiUtils.h"
 #include "nsBidiPresUtils.h"
 #endif // IBMBIDI
+
+using namespace mozilla;
 
 #define CROP_LEFT   "left"
 #define CROP_RIGHT  "right"
@@ -450,7 +452,7 @@ nsTextBoxFrame::PaintTitle(nsIRenderingC
 
     nscoord baseline =
       presContext->RoundAppUnitsToNearestDevPixels(textRect.y + ascent);
-    nsRefPtr<gfxContext> ctx = aRenderingContext.ThebesContext();
+    RefPtr<gfxContext> ctx = aRenderingContext.ThebesContext();
     gfxPoint pt(presContext->AppUnitsToGfxUnits(textRect.x),
                 presContext->AppUnitsToGfxUnits(textRect.y));
     gfxFloat width = presContext->AppUnitsToGfxUnits(textRect.width);
diff --git a/modules/libpr0n/src/imgContainer.cpp b/modules/libpr0n/src/imgContainer.cpp
--- a/modules/libpr0n/src/imgContainer.cpp
+++ b/modules/libpr0n/src/imgContainer.cpp
@@ -58,6 +58,8 @@
 #include "prenv.h"
 
 #include "gfxContext.h"
+
+using namespace mozilla;
 
 /* Accounting for compressed data */
 #if defined(PR_LOGGING)
@@ -977,7 +979,7 @@ void imgContainer::ClearFrame(gfxIImageF
     return;
 
   nsCOMPtr<nsIImage> img(do_GetInterface(aFrame));
-  nsRefPtr<gfxASurface> surf;
+  RefPtr<gfxASurface> surf;
 
   img->LockImagePixels(0);
   img->GetSurface(getter_AddRefs(surf));
@@ -997,7 +999,7 @@ void imgContainer::ClearFrame(gfxIImageF
   }
 
   nsCOMPtr<nsIImage> img(do_GetInterface(aFrame));
-  nsRefPtr<gfxASurface> surf;
+  RefPtr<gfxASurface> surf;
 
   img->LockImagePixels(0);
   img->GetSurface(getter_AddRefs(surf));
@@ -1129,11 +1131,11 @@ nsresult imgContainer::DrawFrameTo(gfxII
   }
 
   nsCOMPtr<nsIImage> srcImg(do_GetInterface(aSrc));
-  nsRefPtr<gfxPattern> srcPatt;
+  RefPtr<gfxPattern> srcPatt;
   srcImg->GetPattern(getter_AddRefs(srcPatt));
 
   nsCOMPtr<nsIImage> dstImg(do_GetInterface(aDst));
-  nsRefPtr<gfxASurface> dstSurf;
+  RefPtr<gfxASurface> dstSurf;
   // Note: dstImage has LockImageData() called on it above, so it's safe to get
   // the surface.
   dstImg->GetSurface(getter_AddRefs(dstSurf));
diff --git a/modules/libpr0n/src/imgTools.cpp b/modules/libpr0n/src/imgTools.cpp
--- a/modules/libpr0n/src/imgTools.cpp
+++ b/modules/libpr0n/src/imgTools.cpp
@@ -55,6 +55,7 @@
 #include "nsWeakReference.h"
 #include "nsIInterfaceRequestorUtils.h"
 
+using namespace mozilla;
 
 /* ========== Utility classes ========== */
 
@@ -298,7 +299,7 @@ NS_IMETHODIMP imgTools::EncodeScaledImag
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIImage> img(do_GetInterface(frame));
-  nsRefPtr<gfxImageSurface> dest;
+  RefPtr<gfxImageSurface> dest;
 
   if (!doScaling) {
     // If we're not scaling the image, use the actual width/height.
@@ -319,7 +320,7 @@ NS_IMETHODIMP imgTools::EncodeScaledImag
     // Prepare to draw a scaled version of the image to a temporary surface...
 
     // Get the source image surface
-    nsRefPtr<gfxPattern> gfxpat;
+    RefPtr<gfxPattern> gfxpat;
     img->GetPattern(getter_AddRefs(gfxpat));
 
     // Create a temporary image surface
diff --git a/view/src/nsViewManager.cpp b/view/src/nsViewManager.cpp
--- a/view/src/nsViewManager.cpp
+++ b/view/src/nsViewManager.cpp
@@ -65,6 +65,8 @@
 #include "gfxContext.h"
 #define NS_STATIC_FOCUS_SUPPRESSOR
 #include "nsIFocusEventSuppressor.h"
+
+using namespace mozilla;
 
 static NS_DEFINE_IID(kBlenderCID, NS_BLENDER_CID);
 static NS_DEFINE_IID(kRegionCID, NS_REGION_CID);
@@ -484,7 +486,7 @@ void nsViewManager::Refresh(nsView *aVie
 
     PRInt32 p2a = mContext->AppUnitsPerDevPixel();
 
-    nsRefPtr<gfxContext> ctx = localcx->ThebesContext();
+    RefPtr<gfxContext> ctx = localcx->ThebesContext();
 
     ctx->Save();
 
diff --git a/widget/src/cocoa/nsChildView.h b/widget/src/cocoa/nsChildView.h
--- a/widget/src/cocoa/nsChildView.h
+++ b/widget/src/cocoa/nsChildView.h
@@ -61,13 +61,14 @@
 #include "nsIEventListener.h"
 #include "nsString.h"
 #include "nsIDragService.h"
+#include "nsIMenuBar.h"
+#include "gfxASurface.h"
 
 #include "nsplugindefs.h"
 
 #import <Carbon/Carbon.h>
 #import <Cocoa/Cocoa.h>
 
-class gfxASurface;
 class nsChildView;
 union nsPluginPort;
 
@@ -405,7 +406,7 @@ protected:
   nsWeakPtr             mAccessible;
 #endif
 
-  nsRefPtr<gfxASurface> mTempThebesSurface;
+  RefPtr<gfxASurface> mTempThebesSurface;
 
   PRPackedBool          mVisible;
   PRPackedBool          mDrawing;
diff --git a/widget/src/cocoa/nsChildView.mm b/widget/src/cocoa/nsChildView.mm
--- a/widget/src/cocoa/nsChildView.mm
+++ b/widget/src/cocoa/nsChildView.mm
@@ -2722,7 +2722,7 @@ NSEvent* gLastDragEvent = nil;
   mGeckoChild->GetBounds(geckoBounds);
 
   NSRect bounds = [self bounds];
-  nsRefPtr<gfxQuartzSurface> targetSurface =
+  RefPtr<gfxQuartzSurface> targetSurface =
     new gfxQuartzSurface(cgContext, gfxSize(bounds.size.width, bounds.size.height));
 
 #ifdef DEBUG_UPDATE
@@ -2735,7 +2735,7 @@ NSEvent* gLastDragEvent = nil;
   fprintf (stderr, "  xform in: [%f %f %f %f %f %f]\n", xform.a, xform.b, xform.c, xform.d, xform.tx, xform.ty);
 #endif
 
-  nsRefPtr<gfxContext> targetContext = new gfxContext(targetSurface);
+  RefPtr<gfxContext> targetContext = new gfxContext(targetSurface);
 
   nsCOMPtr<nsIRenderingContext> rc;
   mGeckoChild->GetDeviceContext()->CreateRenderingContextInstance(*getter_AddRefs(rc));
diff --git a/widget/src/cocoa/nsDeviceContextSpecX.mm b/widget/src/cocoa/nsDeviceContextSpecX.mm
--- a/widget/src/cocoa/nsDeviceContextSpecX.mm
+++ b/widget/src/cocoa/nsDeviceContextSpecX.mm
@@ -210,7 +210,7 @@ NS_IMETHODIMP nsDeviceContextSpecX::GetS
     CGContextRef context;
     ::PMSessionGetCGGraphicsContext(mPrintSession, &context);
 
-    nsRefPtr<gfxASurface> newSurface;
+    RefPtr<gfxASurface> newSurface;
 
     if (context) {
         // Initially, origin is at bottom-left corner of the paper.
@@ -225,8 +225,7 @@ NS_IMETHODIMP nsDeviceContextSpecX::GetS
     if (!newSurface)
         return NS_ERROR_FAILURE;
 
-    *surface = newSurface;
-    NS_ADDREF(*surface);
+    *surface = do_AddRef(newSurface).get();
 
     return NS_OK;
 
diff --git a/widget/src/cocoa/nsDragService.mm b/widget/src/cocoa/nsDragService.mm
--- a/widget/src/cocoa/nsDragService.mm
+++ b/widget/src/cocoa/nsDragService.mm
@@ -170,7 +170,7 @@ nsDragService::ConstructDragImage(nsIDOM
   if ([[NSScreen screens] count] > 0)
     screenPoint.y = NSMaxY([[[NSScreen screens] objectAtIndex:0] frame]) - screenPoint.y;
 
-  nsRefPtr<gfxASurface> surface;
+  RefPtr<gfxASurface> surface;
   nsPresContext* pc;
   nsresult rv = DrawDrag(aDOMNode, aRegion,
                          NSToIntRound(screenPoint.x), NSToIntRound(screenPoint.y),
@@ -186,12 +186,12 @@ nsDragService::ConstructDragImage(nsIDOM
   PRUint32 width = aDragRect->width;
   PRUint32 height = aDragRect->height;
 
-  nsRefPtr<gfxImageSurface> imgSurface = new gfxImageSurface(
+  RefPtr<gfxImageSurface> imgSurface = new gfxImageSurface(
     gfxIntSize(width, height), gfxImageSurface::ImageFormatARGB32);
   if (!imgSurface)
     return nil;
 
-  nsRefPtr<gfxContext> context = new gfxContext(imgSurface);
+  RefPtr<gfxContext> context = new gfxContext(imgSurface);
   if (!context)
     return nil;
 
diff --git a/widget/src/cocoa/nsNativeThemeCocoa.mm b/widget/src/cocoa/nsNativeThemeCocoa.mm
--- a/widget/src/cocoa/nsNativeThemeCocoa.mm
+++ b/widget/src/cocoa/nsNativeThemeCocoa.mm
@@ -998,7 +998,7 @@ nsNativeThemeCocoa::DrawWidgetBackground
   nativeWidgetRect.ScaleInverse(gfxFloat(p2a));
   nativeClipRect.ScaleInverse(gfxFloat(p2a));
 
-  nsRefPtr<gfxContext> thebesCtx = aContext->ThebesContext();
+  RefPtr<gfxContext> thebesCtx = aContext->ThebesContext();
   if (!thebesCtx)
     return NS_ERROR_FAILURE;
 
diff --git a/widget/src/gtk2/nsDeviceContextSpecG.cpp b/widget/src/gtk2/nsDeviceContextSpecG.cpp
--- a/widget/src/gtk2/nsDeviceContextSpecG.cpp
+++ b/widget/src/gtk2/nsDeviceContextSpecG.cpp
@@ -75,6 +75,8 @@
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+
+using namespace mozilla;
 
 /* Ensure that the result is always equal to either PR_TRUE or PR_FALSE */
 #define MAKE_PR_BOOL(val) ((val)?(PR_TRUE):(PR_FALSE))
@@ -463,7 +465,7 @@ NS_IMETHODIMP nsDeviceContextSpecGTK::Ge
   PRInt16 format;
   mPrintSettings->GetOutputFormat(&format);
 
-  nsRefPtr<gfxASurface> surface;
+  RefPtr<gfxASurface> surface;
   gfxSize surfaceSize(width, height);
 
   // Determine the real format with some GTK magic
@@ -494,7 +496,7 @@ NS_IMETHODIMP nsDeviceContextSpecGTK::Ge
   if (!surface)
     return NS_ERROR_OUT_OF_MEMORY;
 
-  surface.swap(*aSurface);
+  *aSurface = surface.forget().get();
 
   return NS_OK;
 }
diff --git a/widget/src/gtk2/nsDragService.cpp b/widget/src/gtk2/nsDragService.cpp
--- a/widget/src/gtk2/nsDragService.cpp
+++ b/widget/src/gtk2/nsDragService.cpp
@@ -68,6 +68,8 @@
 
 // This sets how opaque the drag image is
 #define DRAG_IMAGE_ALPHA_LEVEL 0.5
+
+using namespace mozilla;
 
 static PRLogModuleInfo *sDragLm = NULL;
 
@@ -210,7 +212,7 @@ nsDragService::InvokeDragSession(nsIDOMN
         PRBool needsFallbackIcon = PR_FALSE;
         nsRect dragRect;
         nsPresContext* pc;
-        nsRefPtr<gfxASurface> surface;
+        RefPtr<gfxASurface> surface;
         if (mHasImage || mSelection) {
           DrawDrag(aDOMNode, aRegion, mScreenX, mScreenY,
                    &dragRect, getter_AddRefs(surface), &pc);
@@ -269,13 +271,13 @@ nsDragService::SetAlphaPixmap(gfxASurfac
     gdk_drawable_set_colormap(GDK_DRAWABLE(pixmap), alphaColormap);
 
     // Make a gfxXlibSurface wrapped around the pixmap to render on
-    nsRefPtr<gfxASurface> xPixmapSurface =
+    RefPtr<gfxASurface> xPixmapSurface =
          nsWindow::GetSurfaceForGdkDrawable(GDK_DRAWABLE(pixmap),
                                             dragRect.Size());
     if (!xPixmapSurface)
       return PR_FALSE;
 
-    nsRefPtr<gfxContext> xPixmapCtx = new gfxContext(xPixmapSurface);
+    RefPtr<gfxContext> xPixmapCtx = new gfxContext(xPixmapSurface);
 
     // Clear it...
     xPixmapCtx->SetOperator(gfxContext::OPERATOR_CLEAR);
diff --git a/widget/src/gtk2/nsImageToPixbuf.cpp b/widget/src/gtk2/nsImageToPixbuf.cpp
--- a/widget/src/gtk2/nsImageToPixbuf.cpp
+++ b/widget/src/gtk2/nsImageToPixbuf.cpp
@@ -47,6 +47,8 @@
 
 #include "nsImageToPixbuf.h"
 
+using namespace mozilla;
+
 NS_IMPL_ISUPPORTS1(nsImageToPixbuf, nsIImageToPixbuf)
 
 inline unsigned char
@@ -71,7 +73,7 @@ nsImageToPixbuf::ImageToPixbuf(nsIImage*
     PRInt32 width = aImage->GetWidth(),
             height = aImage->GetHeight();
 
-    nsRefPtr<gfxPattern> pattern;
+    RefPtr<gfxPattern> pattern;
     aImage->GetPattern(getter_AddRefs(pattern));
 
     return PatternToPixbuf(pattern, width, height);
@@ -136,7 +138,7 @@ nsImageToPixbuf::SurfaceToPixbuf(gfxASur
         return nsnull;
     }
 
-    nsRefPtr<gfxImageSurface> imgSurface;
+    RefPtr<gfxImageSurface> imgSurface;
     if (aSurface->GetType() == gfxASurface::SurfaceTypeImage) {
         imgSurface = static_cast<gfxImageSurface*>
                                 (static_cast<gfxASurface*>(aSurface));
@@ -147,7 +149,7 @@ nsImageToPixbuf::SurfaceToPixbuf(gfxASur
         if (!imgSurface)
             return nsnull;
 
-        nsRefPtr<gfxContext> context = new gfxContext(imgSurface);
+        RefPtr<gfxContext> context = new gfxContext(imgSurface);
         if (!context)
             return nsnull;
 
@@ -167,9 +169,9 @@ nsImageToPixbuf::PatternToPixbuf(gfxPatt
         return nsnull;
     }
 
-    nsRefPtr<gfxImageSurface> imgSurface;
+    RefPtr<gfxImageSurface> imgSurface;
     if (aPattern->GetType() == gfxPattern::PATTERN_SURFACE) {
-        nsRefPtr<gfxASurface> surface = aPattern->GetSurface();
+        RefPtr<gfxASurface> surface = aPattern->GetSurface();
         if (surface->GetType() == gfxASurface::SurfaceTypeImage) {
             imgSurface = static_cast<gfxImageSurface*>
                                     (static_cast<gfxASurface*>(surface.get()));
@@ -183,7 +185,7 @@ nsImageToPixbuf::PatternToPixbuf(gfxPatt
         if (!imgSurface)
             return nsnull;
 
-        nsRefPtr<gfxContext> context = new gfxContext(imgSurface);
+        RefPtr<gfxContext> context = new gfxContext(imgSurface);
         if (!context)
             return nsnull;
 
diff --git a/widget/src/gtk2/nsWindow.cpp b/widget/src/gtk2/nsWindow.cpp
--- a/widget/src/gtk2/nsWindow.cpp
+++ b/widget/src/gtk2/nsWindow.cpp
@@ -116,6 +116,8 @@ static const char sAccessibilityKey [] =
 #include "gfxGlitzSurface.h"
 #include "glitz-glx.h"
 #endif
+
+using namespace mozilla;
 
 /* For PrepareNativeWidget */
 static NS_DEFINE_IID(kDeviceContextCID, NS_DEVICE_CONTEXT_CID);
@@ -1677,13 +1679,13 @@ nsWindow::OnExposeEvent(GtkWidget *aWidg
     GetHasTransparentBackground(translucent);
     nsIntRect boundsRect;
     GdkPixmap* bufferPixmap = nsnull;
-    nsRefPtr<gfxASurface> bufferPixmapSurface;
+    RefPtr<gfxASurface> bufferPixmapSurface;
 
     updateRegion->GetBoundingBox(&boundsRect.x, &boundsRect.y,
                                  &boundsRect.width, &boundsRect.height);
 
     // do double-buffering and clipping here
-    nsRefPtr<gfxContext> ctx = rc->ThebesContext();
+    RefPtr<gfxContext> ctx = rc->ThebesContext();
     ctx->Save();
     ctx->NewPath();
     if (translucent) {
@@ -1765,18 +1767,18 @@ nsWindow::OnExposeEvent(GtkWidget *aWidg
     if (NS_LIKELY(!mIsDestroyed)) {
         if (status != nsEventStatus_eIgnore) {
             if (translucent) {
-                nsRefPtr<gfxPattern> pattern = ctx->PopGroup();
+                RefPtr<gfxPattern> pattern = ctx->PopGroup();
                 ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
                 ctx->SetPattern(pattern);
                 ctx->Paint();
 
-                nsRefPtr<gfxImageSurface> img =
+                RefPtr<gfxImageSurface> img =
                     new gfxImageSurface(gfxIntSize(boundsRect.width, boundsRect.height),
                                         gfxImageSurface::ImageFormatA8);
                 if (img && !img->CairoStatus()) {
                     img->SetDeviceOffset(gfxPoint(-boundsRect.x, -boundsRect.y));
             
-                    nsRefPtr<gfxContext> imgCtx = new gfxContext(img);
+                    RefPtr<gfxContext> imgCtx = new gfxContext(img);
                     if (imgCtx) {
                         imgCtx->SetPattern(pattern);
                         imgCtx->SetOperator(gfxContext::OPERATOR_SOURCE);
@@ -6204,7 +6206,7 @@ IM_get_input_context(nsWindow *aWindow)
 
 #endif
 
-/* static */ already_AddRefed<gfxASurface>
+/* static */ AddRefed<gfxASurface>
 nsWindow::GetSurfaceForGdkDrawable(GdkDrawable* aDrawable,
                                    const nsSize& aSize)
 {
@@ -6213,10 +6215,8 @@ nsWindow::GetSurfaceForGdkDrawable(GdkDr
     Display* xDisplay = gdk_x11_drawable_get_xdisplay(aDrawable);
     Drawable xDrawable = gdk_x11_drawable_get_xid(aDrawable);
 
-    gfxASurface* result = new gfxXlibSurface(xDisplay, xDrawable, xVisual,
-                                       gfxIntSize(aSize.width, aSize.height));
-    NS_IF_ADDREF(result);
-    return result;
+    return do_AddRef(new gfxXlibSurface(xDisplay, xDrawable, xVisual,
+                                        gfxIntSize(aSize.width, aSize.height)));
 }
 
 // return the gfxASurface for rendering to this widget
diff --git a/widget/src/gtk2/nsWindow.h b/widget/src/gtk2/nsWindow.h
--- a/widget/src/gtk2/nsWindow.h
+++ b/widget/src/gtk2/nsWindow.h
@@ -40,9 +40,8 @@
 #ifndef __nsWindow_h__
 #define __nsWindow_h__
 
-#include "nsAutoPtr.h"
-
 #include "nsCommonWidget.h"
+#include "gfxTypes.h"
 
 #include "mozcontainer.h"
 #include "mozdrawingarea.h"
@@ -367,8 +366,8 @@ public:
 
     gfxASurface       *GetThebesSurface();
 
-    static already_AddRefed<gfxASurface> GetSurfaceForGdkDrawable(GdkDrawable* aDrawable,
-                                                                  const nsSize& aSize);
+    static mozilla::AddRefed<gfxASurface> GetSurfaceForGdkDrawable(GdkDrawable* aDrawable,
+                                                                   const nsSize& aSize);
 
 #ifdef ACCESSIBILITY
     static PRBool      sAccessibilityEnabled;
@@ -404,7 +403,7 @@ private:
     PRInt32             mTransparencyBitmapWidth;
     PRInt32             mTransparencyBitmapHeight;
 
-    nsRefPtr<gfxASurface> mThebesSurface;
+    mozilla::RefPtr<gfxASurface> mThebesSurface;
 
 #ifdef ACCESSIBILITY
     nsCOMPtr<nsIAccessible> mRootAccessible;
diff --git a/widget/src/windows/nsDeviceContextSpecWin.cpp b/widget/src/windows/nsDeviceContextSpecWin.cpp
--- a/widget/src/windows/nsDeviceContextSpecWin.cpp
+++ b/widget/src/windows/nsDeviceContextSpecWin.cpp
@@ -516,7 +516,7 @@ NS_IMETHODIMP nsDeviceContextSpecWin::Ge
 {
   NS_ASSERTION(mDevMode, "DevMode can't be NULL here");
 
-  nsRefPtr<gfxASurface> newSurface;
+  RefPtr<gfxASurface> newSurface;
 
   PRInt16 outputFormat;
   mPrintSettings->GetOutputFormat(&outputFormat);
@@ -552,8 +552,7 @@ NS_IMETHODIMP nsDeviceContextSpecWin::Ge
   }
 
   if (newSurface) {
-    *surface = newSurface;
-    NS_ADDREF(*surface);
+    *surface = newSurface.forget().get();
     return NS_OK;
   }
 
diff --git a/widget/src/windows/nsDragService.cpp b/widget/src/windows/nsDragService.cpp
--- a/widget/src/windows/nsDragService.cpp
+++ b/widget/src/windows/nsDragService.cpp
@@ -110,7 +110,7 @@ nsDragService::CreateDragImage(nsIDOMNod
 
   // Prepare the drag image
   nsRect dragRect;
-  nsRefPtr<gfxASurface> surface;
+  RefPtr<gfxASurface> surface;
   nsPresContext* pc;
   DrawDrag(aDOMNode, aRegion,
            mScreenX, mScreenY,
@@ -125,13 +125,13 @@ nsDragService::CreateDragImage(nsIDOMNod
 
   psdi->crColorKey = CLR_NONE;
 
-  nsRefPtr<gfxImageSurface> imgSurface = new gfxImageSurface(
+  RefPtr<gfxImageSurface> imgSurface = new gfxImageSurface(
     gfxIntSize(bmWidth, bmHeight), 
     gfxImageSurface::ImageFormatARGB32);
   if (!imgSurface)
     return PR_FALSE;
 
-  nsRefPtr<gfxContext> context = new gfxContext(imgSurface);
+  RefPtr<gfxContext> context = new gfxContext(imgSurface);
   if (!context)
     return PR_FALSE;
 
diff --git a/widget/src/windows/nsNativeThemeWin.cpp b/widget/src/windows/nsNativeThemeWin.cpp
--- a/widget/src/windows/nsNativeThemeWin.cpp
+++ b/widget/src/windows/nsNativeThemeWin.cpp
@@ -1262,7 +1262,7 @@ nsNativeThemeWin::DrawWidgetBackground(n
     }
   }
 
-  nsRefPtr<gfxContext> ctx = aContext->ThebesContext();
+  RefPtr<gfxContext> ctx = aContext->ThebesContext();
 
   gfxWindowsNativeDrawing nativeDrawing(ctx, cr, GetWidgetNativeDrawingFlags(aWidgetType));
 
@@ -2672,7 +2672,7 @@ nsresult nsNativeThemeWin::ClassicDrawWi
   tr.ScaleInverse(p2a);
   cr.ScaleInverse(p2a);
 
-  nsRefPtr<gfxContext> ctx = aContext->ThebesContext();
+  RefPtr<gfxContext> ctx = aContext->ThebesContext();
 
   gfxWindowsNativeDrawing nativeDrawing(ctx, cr, GetWidgetNativeDrawingFlags(aWidgetType));
 
diff --git a/widget/src/windows/nsWindow.cpp b/widget/src/windows/nsWindow.cpp
--- a/widget/src/windows/nsWindow.cpp
+++ b/widget/src/windows/nsWindow.cpp
@@ -5813,17 +5813,17 @@ PRBool nsWindow::OnPaint(HDC aDC)
 #endif // NS_DEBUG
 
 #ifdef MOZ_XUL
-      nsRefPtr<gfxASurface> targetSurface;
+      RefPtr<gfxASurface> targetSurface;
       if (mIsTransparent) {
         targetSurface = mTransparentSurface;
       } else {
         targetSurface = new gfxWindowsSurface(hDC);
       }
 #else
-      nsRefPtr<gfxASurface> targetSurface = new gfxWindowsSurface(hDC);
-#endif
-
-      nsRefPtr<gfxContext> thebesContext = new gfxContext(targetSurface);
+      RefPtr<gfxASurface> targetSurface = new gfxWindowsSurface(hDC);
+#endif
+
+      RefPtr<gfxContext> thebesContext = new gfxContext(targetSurface);
 
 #ifdef MOZ_XUL
       if (mIsTransparent) {
diff --git a/widget/src/windows/nsWindow.h b/widget/src/windows/nsWindow.h
--- a/widget/src/windows/nsWindow.h
+++ b/widget/src/windows/nsWindow.h
@@ -420,7 +420,7 @@ protected:
 
 #ifdef MOZ_XUL
   // use layered windows to support full 256 level alpha translucency
-  nsRefPtr<gfxWindowsSurface> mTransparentSurface;
+  RefPtr<gfxWindowsSurface> mTransparentSurface;
 
   HDC           mMemoryDC;
   HBITMAP       mMemoryBitmap;
diff --git a/widget/src/xpwidgets/nsBaseDragService.cpp b/widget/src/xpwidgets/nsBaseDragService.cpp
--- a/widget/src/xpwidgets/nsBaseDragService.cpp
+++ b/widget/src/xpwidgets/nsBaseDragService.cpp
@@ -73,6 +73,8 @@
 
 #include "gfxContext.h"
 #include "gfxImageSurface.h"
+
+using namespace mozilla;
 
 #define DRAGIMAGES_PREF "nglayout.enable_drag_images"
 
@@ -445,9 +447,9 @@ nsBaseDragService::DrawDrag(nsIDOMNode* 
   // draw the image for selections
   if (mSelection) {
     nsPoint pnt(aScreenDragRect->x, aScreenDragRect->y);
-    nsRefPtr<gfxASurface> surface = presShell->RenderSelection(mSelection, pnt, aScreenDragRect);
-    *aSurface = surface;
-    NS_IF_ADDREF(*aSurface);
+
+    *aSurface = presShell->
+      RenderSelection(mSelection, pnt, aScreenDragRect).get();
     return NS_OK;
   }
 
@@ -469,8 +471,8 @@ nsBaseDragService::DrawDrag(nsIDOMNode* 
     aRegion->GetRegion(getter_AddRefs(clipRegion));
 
   nsPoint pnt(aScreenDragRect->x, aScreenDragRect->y);
-  nsRefPtr<gfxASurface> surface = presShell->RenderNode(dragNode, clipRegion,
-                                                        pnt, aScreenDragRect);
+  RefPtr<gfxASurface> surface = presShell->RenderNode(dragNode, clipRegion,
+                                                         pnt, aScreenDragRect);
 
   // if an image was specified, reposition the drag rectangle to
   // the supplied offset in mImageX and mImageY.
@@ -479,8 +481,7 @@ nsBaseDragService::DrawDrag(nsIDOMNode* 
     aScreenDragRect->y = aScreenY - mImageY;
   }
 
-  *aSurface = surface;
-  NS_IF_ADDREF(*aSurface);
+  *aSurface = surface.forget().get();
 
   return NS_OK;
 }
@@ -548,14 +549,14 @@ nsBaseDragService::DrawDragForImage(nsPr
     aScreenDragRect->height = destRect.height;
   }
 
-  nsRefPtr<gfxImageSurface> surface =
+  RefPtr<gfxImageSurface> surface =
     new gfxImageSurface(gfxIntSize(destRect.width, destRect.height),
                         gfxImageSurface::ImageFormatARGB32);
   if (!surface)
     return NS_ERROR_FAILURE;
 
   *aSurface = surface;
-  NS_ADDREF(*aSurface);
+  surface->AddReference();
 
   nsCOMPtr<nsIRenderingContext> rc;
   deviceContext->CreateRenderingContextInstance(*getter_AddRefs(rc));