Bug 1231550 - Use DrawTarget instead of gfxContext and/or nsRenderingContext in many places in font/text code. r=jfkthame.
authorNicholas Nethercote <nnethercote@mozilla.com>
Tue, 15 Dec 2015 13:56:41 -0800
changeset 278417 290f666471a0177f984f05d5c9933914d2d11443
parent 278416 c82bd0fbe6b6f46e3a0600e4ac835cfbabff9aaf
child 278418 3a785337924021ba18a5252775472a2ead8a50f6
push id29850
push usercbook@mozilla.com
push dateTue, 05 Jan 2016 10:59:10 +0000
treeherdermozilla-central@29258f59e545 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjfkthame
bugs1231550
milestone46.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1231550 - Use DrawTarget instead of gfxContext and/or nsRenderingContext in many places in font/text code. r=jfkthame. AutoTextRun now only needs a DrawTarget instead of an nsRenderingContext, and similar nsRenderingContext/gfxContext-to-DrawTarget replacements can be propagated a long way up the call graph. This patch replaces 93 occurrences of nsRenderingContext and 135 occurrences of gfxContext with DrawTarget; that's 13% of them. The patch is mostly plumbing changes. A couple of not-entirely-plumbing changes: - It adds a comment about the null check in gfxGlyphExtents::GetTightGlyphExtentsAppUnits(). - A couple of functions simply had an unused gfxContext or nsRenderingContext parameter removed, e.g. SetLineBreaks().
dom/canvas/CanvasRenderingContext2D.cpp
gfx/src/nsFontMetrics.cpp
gfx/src/nsFontMetrics.h
gfx/tests/gtest/gfxWordCacheTest.cpp
gfx/thebes/gfxCoreTextShaper.cpp
gfx/thebes/gfxCoreTextShaper.h
gfx/thebes/gfxDWriteFonts.cpp
gfx/thebes/gfxDWriteFonts.h
gfx/thebes/gfxFT2Fonts.cpp
gfx/thebes/gfxFT2Fonts.h
gfx/thebes/gfxFont.cpp
gfx/thebes/gfxFont.h
gfx/thebes/gfxGDIFont.cpp
gfx/thebes/gfxGDIFont.h
gfx/thebes/gfxGlyphExtents.cpp
gfx/thebes/gfxGlyphExtents.h
gfx/thebes/gfxGraphiteShaper.cpp
gfx/thebes/gfxGraphiteShaper.h
gfx/thebes/gfxHarfBuzzShaper.cpp
gfx/thebes/gfxHarfBuzzShaper.h
gfx/thebes/gfxMacFont.cpp
gfx/thebes/gfxMacFont.h
gfx/thebes/gfxTextRun.cpp
gfx/thebes/gfxTextRun.h
layout/base/nsBidiPresUtils.cpp
layout/base/nsBidiPresUtils.h
layout/base/nsLayoutUtils.cpp
layout/base/nsLayoutUtils.h
layout/base/nsPresShell.cpp
layout/doc/obsolete/line-layout.html
layout/generic/MathMLTextRunFactory.cpp
layout/generic/MathMLTextRunFactory.h
layout/generic/TextOverflow.cpp
layout/generic/nsBlockFrame.cpp
layout/generic/nsBlockFrame.h
layout/generic/nsBulletFrame.cpp
layout/generic/nsFrame.cpp
layout/generic/nsFrame.h
layout/generic/nsIFrame.h
layout/generic/nsImageFrame.cpp
layout/generic/nsInlineFrame.cpp
layout/generic/nsInlineFrame.h
layout/generic/nsLineLayout.cpp
layout/generic/nsPageFrame.cpp
layout/generic/nsRubyBaseContainerFrame.cpp
layout/generic/nsTextFrame.cpp
layout/generic/nsTextFrame.h
layout/generic/nsTextRunTransformations.cpp
layout/generic/nsTextRunTransformations.h
layout/mathml/nsIMathMLFrame.h
layout/mathml/nsMathMLChar.cpp
layout/mathml/nsMathMLChar.h
layout/mathml/nsMathMLContainerFrame.cpp
layout/mathml/nsMathMLContainerFrame.h
layout/mathml/nsMathMLFrame.cpp
layout/mathml/nsMathMLFrame.h
layout/mathml/nsMathMLSelectedFrame.cpp
layout/mathml/nsMathMLSelectedFrame.h
layout/mathml/nsMathMLTokenFrame.cpp
layout/mathml/nsMathMLTokenFrame.h
layout/mathml/nsMathMLmencloseFrame.cpp
layout/mathml/nsMathMLmencloseFrame.h
layout/mathml/nsMathMLmfencedFrame.cpp
layout/mathml/nsMathMLmfencedFrame.h
layout/mathml/nsMathMLmfracFrame.cpp
layout/mathml/nsMathMLmfracFrame.h
layout/mathml/nsMathMLmmultiscriptsFrame.cpp
layout/mathml/nsMathMLmmultiscriptsFrame.h
layout/mathml/nsMathMLmoFrame.cpp
layout/mathml/nsMathMLmoFrame.h
layout/mathml/nsMathMLmpaddedFrame.cpp
layout/mathml/nsMathMLmpaddedFrame.h
layout/mathml/nsMathMLmrootFrame.cpp
layout/mathml/nsMathMLmspaceFrame.cpp
layout/mathml/nsMathMLmspaceFrame.h
layout/mathml/nsMathMLmtableFrame.cpp
layout/mathml/nsMathMLmunderoverFrame.cpp
layout/mathml/nsMathMLmunderoverFrame.h
layout/xul/nsTextBoxFrame.cpp
layout/xul/nsTextBoxFrame.h
layout/xul/tree/nsTreeBodyFrame.cpp
layout/xul/tree/nsTreeBodyFrame.h
--- a/dom/canvas/CanvasRenderingContext2D.cpp
+++ b/dom/canvas/CanvasRenderingContext2D.cpp
@@ -3453,30 +3453,30 @@ struct MOZ_STACK_CLASS CanvasBidiProcess
     uint32_t flags = mTextRunFlags;
     if (direction == NSBIDI_RTL) {
       flags |= gfxTextRunFactory::TEXT_IS_RTL;
     } else {
       flags &= ~gfxTextRunFactory::TEXT_IS_RTL;
     }
     mTextRun = mFontgrp->MakeTextRun(text,
                                      length,
-                                     mThebes,
+                                     mThebes->GetDrawTarget(),
                                      mAppUnitsPerDevPixel,
                                      flags,
                                      mMissingFonts);
   }
 
   virtual nscoord GetWidth()
   {
     gfxTextRun::Metrics textRunMetrics = mTextRun->MeasureText(0,
                                                                mTextRun->GetLength(),
                                                                mDoMeasureBoundingBox ?
                                                                  gfxFont::TIGHT_INK_EXTENTS :
                                                                  gfxFont::LOOSE_INK_EXTENTS,
-                                                               mThebes,
+                                                               mThebes->GetDrawTarget(),
                                                                nullptr);
 
     // this only measures the height; the total width is gotten from the
     // the return value of ProcessText.
     if (mDoMeasureBoundingBox) {
       textRunMetrics.mBoundingBox.Scale(1.0 / mAppUnitsPerDevPixel);
       mBoundingBox = mBoundingBox.Union(textRunMetrics.mBoundingBox);
     }
@@ -3502,17 +3502,17 @@ struct MOZ_STACK_CLASS CanvasBidiProcess
       // glyph string on OS X and DWrite where textrun widths may
       // involve fractional pixels.
       gfxTextRun::Metrics textRunMetrics =
         mTextRun->MeasureText(0,
                               mTextRun->GetLength(),
                               mDoMeasureBoundingBox ?
                                   gfxFont::TIGHT_INK_EXTENTS :
                                   gfxFont::LOOSE_INK_EXTENTS,
-                              mThebes,
+                              mThebes->GetDrawTarget(),
                               nullptr);
       inlineCoord += textRunMetrics.mAdvanceWidth;
       // old code was:
       //   point.x += width * mAppUnitsPerDevPixel;
       // TODO: restore this if/when we move to fractional coords
       // throughout the text layout process
     }
 
--- a/gfx/src/nsFontMetrics.cpp
+++ b/gfx/src/nsFontMetrics.cpp
@@ -22,33 +22,35 @@
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT
 
 class gfxUserFontSet;
 
 namespace {
 
 class AutoTextRun {
 public:
-    AutoTextRun(nsFontMetrics* aMetrics, nsRenderingContext* aRC,
+    typedef mozilla::gfx::DrawTarget DrawTarget;
+
+    AutoTextRun(nsFontMetrics* aMetrics, DrawTarget* aDrawTarget,
                 const char* aString, int32_t aLength)
     {
         mTextRun = aMetrics->GetThebesFontGroup()->MakeTextRun(
             reinterpret_cast<const uint8_t*>(aString), aLength,
-            aRC->ThebesContext(),
+            aDrawTarget,
             aMetrics->AppUnitsPerDevPixel(),
             ComputeFlags(aMetrics),
             nullptr);
     }
 
-    AutoTextRun(nsFontMetrics* aMetrics, nsRenderingContext* aRC,
+    AutoTextRun(nsFontMetrics* aMetrics, DrawTarget* aDrawTarget,
                 const char16_t* aString, int32_t aLength)
     {
         mTextRun = aMetrics->GetThebesFontGroup()->MakeTextRun(
             aString, aLength,
-            aRC->ThebesContext(),
+            aDrawTarget,
             aMetrics->AppUnitsPerDevPixel(),
             ComputeFlags(aMetrics),
             nullptr);
     }
 
     gfxTextRun *get() { return mTextRun; }
     gfxTextRun *operator->() { return mTextRun; }
 
@@ -86,17 +88,17 @@ public:
     virtual int8_t GetHyphensOption() {
         NS_ERROR("This shouldn't be called because we never call BreakAndMeasureText");
         return NS_STYLE_HYPHENS_NONE;
     }
     virtual gfxFloat GetHyphenWidth() {
         NS_ERROR("This shouldn't be called because we never enable hyphens");
         return 0;
     }
-    virtual already_AddRefed<gfxContext> GetContext() {
+    virtual already_AddRefed<mozilla::gfx::DrawTarget> GetDrawTarget() {
         NS_ERROR("This shouldn't be called because we never enable hyphens");
         return nullptr;
     }
     virtual uint32_t GetAppUnitsPerDevUnit() {
         NS_ERROR("This shouldn't be called because we never enable hyphens");
         return 60;
     }
     virtual void GetSpacing(uint32_t aStart, uint32_t aLength,
@@ -308,57 +310,57 @@ nsFontMetrics::GetMaxStringLength()
     const gfxFont::Metrics& m = GetMetrics();
     const double x = 32767.0 / m.maxAdvance;
     int32_t len = (int32_t)floor(x);
     return std::max(1, len);
 }
 
 nscoord
 nsFontMetrics::GetWidth(const char* aString, uint32_t aLength,
-                        nsRenderingContext *aContext)
+                        DrawTarget* aDrawTarget)
 {
     if (aLength == 0)
         return 0;
 
     if (aLength == 1 && aString[0] == ' ')
         return SpaceWidth();
 
     StubPropertyProvider provider;
-    AutoTextRun textRun(this, aContext, aString, aLength);
+    AutoTextRun textRun(this, aDrawTarget, aString, aLength);
     return textRun.get() ?
         NSToCoordRound(textRun->GetAdvanceWidth(0, aLength, &provider)) : 0;
 }
 
 nscoord
 nsFontMetrics::GetWidth(const char16_t* aString, uint32_t aLength,
-                        nsRenderingContext *aContext)
+                        DrawTarget* aDrawTarget)
 {
     if (aLength == 0)
         return 0;
 
     if (aLength == 1 && aString[0] == ' ')
         return SpaceWidth();
 
     StubPropertyProvider provider;
-    AutoTextRun textRun(this, aContext, aString, aLength);
+    AutoTextRun textRun(this, aDrawTarget, aString, aLength);
     return textRun.get() ?
         NSToCoordRound(textRun->GetAdvanceWidth(0, aLength, &provider)) : 0;
 }
 
 // Draw a string using this font handle on the surface passed in.
 void
 nsFontMetrics::DrawString(const char *aString, uint32_t aLength,
                           nscoord aX, nscoord aY,
                           nsRenderingContext *aContext)
 {
     if (aLength == 0)
         return;
 
     StubPropertyProvider provider;
-    AutoTextRun textRun(this, aContext, aString, aLength);
+    AutoTextRun textRun(this, aContext->GetDrawTarget(), aString, aLength);
     if (!textRun.get()) {
         return;
     }
     gfxPoint pt(aX, aY);
     if (mTextRunRTL) {
         if (mVertical) {
             pt.y += textRun->GetAdvanceWidth(0, aLength, &provider);
         } else {
@@ -368,70 +370,70 @@ nsFontMetrics::DrawString(const char *aS
     textRun->Draw(aContext->ThebesContext(), pt, DrawMode::GLYPH_FILL, 0, aLength,
                   &provider, nullptr, nullptr);
 }
 
 void
 nsFontMetrics::DrawString(const char16_t* aString, uint32_t aLength,
                           nscoord aX, nscoord aY,
                           nsRenderingContext *aContext,
-                          nsRenderingContext *aTextRunConstructionContext)
+                          DrawTarget* aTextRunConstructionDrawTarget)
 {
     if (aLength == 0)
         return;
 
     StubPropertyProvider provider;
-    AutoTextRun textRun(this, aTextRunConstructionContext, aString, aLength);
+    AutoTextRun textRun(this, aTextRunConstructionDrawTarget, aString, aLength);
     if (!textRun.get()) {
         return;
     }
     gfxPoint pt(aX, aY);
     if (mTextRunRTL) {
         if (mVertical) {
             pt.y += textRun->GetAdvanceWidth(0, aLength, &provider);
         } else {
             pt.x += textRun->GetAdvanceWidth(0, aLength, &provider);
         }
     }
     textRun->Draw(aContext->ThebesContext(), pt, DrawMode::GLYPH_FILL, 0, aLength,
                   &provider, nullptr, nullptr);
 }
 
 static nsBoundingMetrics
-GetTextBoundingMetrics(nsFontMetrics* aMetrics, const char16_t *aString, uint32_t aLength,
-                       nsRenderingContext *aContext, gfxFont::BoundingBoxType aType)
+GetTextBoundingMetrics(nsFontMetrics* aMetrics, const char16_t* aString,
+                       uint32_t aLength, mozilla::gfx::DrawTarget* aDrawTarget,
+                       gfxFont::BoundingBoxType aType)
 {
     if (aLength == 0)
         return nsBoundingMetrics();
 
     StubPropertyProvider provider;
-    AutoTextRun textRun(aMetrics, aContext, aString, aLength);
+    AutoTextRun textRun(aMetrics, aDrawTarget, aString, aLength);
     nsBoundingMetrics m;
     if (textRun.get()) {
         gfxTextRun::Metrics theMetrics =
-            textRun->MeasureText(0, aLength,
-                                 aType,
-                                 aContext->ThebesContext(), &provider);
+            textRun->MeasureText(0, aLength, aType, aDrawTarget, &provider);
 
         m.leftBearing  = NSToCoordFloor( theMetrics.mBoundingBox.X());
         m.rightBearing = NSToCoordCeil(  theMetrics.mBoundingBox.XMost());
         m.ascent       = NSToCoordCeil( -theMetrics.mBoundingBox.Y());
         m.descent      = NSToCoordCeil(  theMetrics.mBoundingBox.YMost());
         m.width        = NSToCoordRound( theMetrics.mAdvanceWidth);
     }
     return m;
 }
 
 nsBoundingMetrics
 nsFontMetrics::GetBoundingMetrics(const char16_t *aString, uint32_t aLength,
-                                  nsRenderingContext *aContext)
+                                  DrawTarget* aDrawTarget)
 {
-  return GetTextBoundingMetrics(this, aString, aLength, aContext, gfxFont::TIGHT_HINTED_OUTLINE_EXTENTS);
-  
+  return GetTextBoundingMetrics(this, aString, aLength, aDrawTarget,
+                                gfxFont::TIGHT_HINTED_OUTLINE_EXTENTS);
 }
 
 nsBoundingMetrics
 nsFontMetrics::GetInkBoundsForVisualOverflow(const char16_t *aString, uint32_t aLength,
-                                             nsRenderingContext *aContext)
+                                             DrawTarget* aDrawTarget)
 {
-  return GetTextBoundingMetrics(this, aString, aLength, aContext, gfxFont::LOOSE_INK_EXTENTS);
+  return GetTextBoundingMetrics(this, aString, aLength, aDrawTarget,
+                                gfxFont::LOOSE_INK_EXTENTS);
 }
 
--- a/gfx/src/nsFontMetrics.h
+++ b/gfx/src/nsFontMetrics.h
@@ -41,16 +41,18 @@ struct nsBoundingMetrics;
  * the em height (for the CSS "em" unit), and we use the first Western
  * font's metrics for that purpose. The platform-specific
  * implementations are expected to select non-Western fonts that "fit"
  * reasonably well with the Western font that is loaded at Init time.
  */
 class nsFontMetrics final
 {
 public:
+    typedef mozilla::gfx::DrawTarget DrawTarget;
+
     nsFontMetrics();
 
     NS_INLINE_DECL_REFCOUNTING(nsFontMetrics)
 
     /**
      * Initialize the font metrics. Call this after creating the font metrics.
      * Font metrics you get from the font cache do NOT need to be initialized
      *
@@ -182,38 +184,38 @@ public:
     gfxFont::Orientation Orientation() const { return mOrientation; }
 
     int32_t GetMaxStringLength();
 
     // Get the width for this string.  aWidth will be updated with the
     // width in points, not twips.  Callers must convert it if they
     // want it in another format.
     nscoord GetWidth(const char* aString, uint32_t aLength,
-                     nsRenderingContext *aContext);
+                     DrawTarget* aDrawTarget);
     nscoord GetWidth(const char16_t* aString, uint32_t aLength,
-                     nsRenderingContext *aContext);
+                     DrawTarget* aDrawTarget);
 
     // Draw a string using this font handle on the surface passed in.
     void DrawString(const char *aString, uint32_t aLength,
                     nscoord aX, nscoord aY,
                     nsRenderingContext *aContext);
     void DrawString(const char16_t* aString, uint32_t aLength,
                     nscoord aX, nscoord aY,
                     nsRenderingContext *aContext,
-                    nsRenderingContext *aTextRunConstructionContext);
+                    DrawTarget* aTextRunConstructionDrawTarget);
 
     nsBoundingMetrics GetBoundingMetrics(const char16_t *aString,
                                          uint32_t aLength,
-                                         nsRenderingContext *aContext);
+                                         DrawTarget* aDrawTarget);
 
     // Returns the LOOSE_INK_EXTENTS bounds of the text for determing the
     // overflow area of the string.
     nsBoundingMetrics GetInkBoundsForVisualOverflow(const char16_t *aString,
                                                     uint32_t aLength,
-                                                    nsRenderingContext *aContext);
+                                                    DrawTarget* aDrawTarget);
 
     void SetTextRunRTL(bool aIsRTL) { mTextRunRTL = aIsRTL; }
     bool GetTextRunRTL() const { return mTextRunRTL; }
 
     void SetVertical(bool aVertical) { mVertical = aVertical; }
     bool GetVertical() const { return mVertical; }
 
     void SetTextOrientation(uint8_t aTextOrientation)
--- a/gfx/tests/gtest/gfxWordCacheTest.cpp
+++ b/gfx/tests/gtest/gfxWordCacheTest.cpp
@@ -76,50 +76,48 @@ MakeTextRun(const char16_t *aText, uint3
   nsresult rv = gTextRuns->AddObject(textRun);
   if (NS_FAILED(rv)) {
     gTextRuns->RemoveFromCache(textRun);
     return nullptr;
   }
   return textRun.forget();
 }
 
-static already_AddRefed<gfxContext>
-MakeContext ()
+static already_AddRefed<DrawTarget>
+MakeDrawTarget()
 {
   const int size = 200;
 
   RefPtr<DrawTarget> drawTarget = gfxPlatform::GetPlatform()->
       CreateOffscreenContentDrawTarget(IntSize(size, size),
                                        SurfaceFormat::B8G8R8X8);
-  RefPtr<gfxContext> ctx = new gfxContext(drawTarget);
-
-  return ctx.forget();
+  return drawTarget.forget();
 }
 
 TEST(Gfx, WordCache) {
   gTextRuns = new FrameTextRunCache();
 
-  RefPtr<gfxContext> ctx = MakeContext();
+  RefPtr<DrawTarget> dt = MakeDrawTarget();
   {
     gfxFontStyle style(mozilla::gfx::FontStyle::NORMAL,
                        139,
                        10.0,
                        0,
                        NS_NewPermanentAtom(NS_LITERAL_STRING("en")),
                        0.0,
                        false, false,
                        NS_LITERAL_STRING(""));
 
     RefPtr<gfxFontGroup> fontGroup =
       gfxPlatform::GetPlatform()->CreateFontGroup(
         NS_LITERAL_STRING("Geneva, MS Sans Serif, Helvetica,serif"), &style,
         nullptr, nullptr, 1.0);
 
     gfxTextRunFactory::Parameters params = {
-      ctx, nullptr, nullptr, nullptr, 0, 60
+      dt, nullptr, nullptr, nullptr, 0, 60
     };
 
     uint32_t flags = gfxTextRunFactory::TEXT_IS_PERSISTENT;
 
     // First load an Arabic word into the cache
     const char cString[] = "\xd8\xaa\xd9\x85";
     nsDependentCString cStr(cString);
     NS_ConvertUTF8toUTF16 str(cStr);
--- a/gfx/thebes/gfxCoreTextShaper.cpp
+++ b/gfx/thebes/gfxCoreTextShaper.cpp
@@ -110,17 +110,17 @@ gfxCoreTextShaper::~gfxCoreTextShaper()
 
 static bool
 IsBuggyIndicScript(int32_t aScript)
 {
     return aScript == MOZ_SCRIPT_BENGALI || aScript == MOZ_SCRIPT_KANNADA;
 }
 
 bool
-gfxCoreTextShaper::ShapeText(gfxContext      *aContext,
+gfxCoreTextShaper::ShapeText(DrawTarget      *aDrawTarget,
                              const char16_t *aText,
                              uint32_t         aOffset,
                              uint32_t         aLength,
                              int32_t          aScript,
                              bool             aVertical,
                              gfxShapedText   *aShapedText)
 {
     // Create a CFAttributedString with text and style info, so we can use CoreText to lay it out.
--- a/gfx/thebes/gfxCoreTextShaper.h
+++ b/gfx/thebes/gfxCoreTextShaper.h
@@ -13,17 +13,17 @@
 class gfxMacFont;
 
 class gfxCoreTextShaper : public gfxFontShaper {
 public:
     explicit gfxCoreTextShaper(gfxMacFont *aFont);
 
     virtual ~gfxCoreTextShaper();
 
-    virtual bool ShapeText(gfxContext      *aContext,
+    virtual bool ShapeText(DrawTarget      *aDrawTarget,
                            const char16_t *aText,
                            uint32_t         aOffset,
                            uint32_t         aLength,
                            int32_t          aScript,
                            bool             aVertical,
                            gfxShapedText   *aShapedText);
 
     // clean up static objects that may have been cached
--- a/gfx/thebes/gfxDWriteFonts.cpp
+++ b/gfx/thebes/gfxDWriteFonts.cpp
@@ -539,27 +539,26 @@ gfxDWriteFont::GetCairoScaledFont()
                  cairo_scaled_font_status(mScaledFont) 
                    == CAIRO_STATUS_SUCCESS,
                  "Failed to make scaled font");
 
     return mScaledFont;
 }
 
 gfxFont::RunMetrics
-gfxDWriteFont::Measure(gfxTextRun *aTextRun,
-                    uint32_t aStart, uint32_t aEnd,
-                    BoundingBoxType aBoundingBoxType,
-                    gfxContext *aRefContext,
-                    Spacing *aSpacing,
-                    uint16_t aOrientation)
+gfxDWriteFont::Measure(gfxTextRun* aTextRun,
+                       uint32_t aStart, uint32_t aEnd,
+                       BoundingBoxType aBoundingBoxType,
+                       DrawTarget* aRefDrawTarget,
+                       Spacing* aSpacing,
+                       uint16_t aOrientation)
 {
     gfxFont::RunMetrics metrics =
-        gfxFont::Measure(aTextRun, aStart, aEnd,
-                         aBoundingBoxType, aRefContext, aSpacing,
-                         aOrientation);
+        gfxFont::Measure(aTextRun, aStart, aEnd, aBoundingBoxType,
+                         aRefDrawTarget, aSpacing, aOrientation);
 
     // if aBoundingBoxType is LOOSE_INK_EXTENTS
     // and the underlying cairo font may be antialiased,
     // we can't trust Windows to have considered all the pixels
     // so we need to add "padding" to the bounds.
     // (see bugs 475968, 439831, compare also bug 445087)
     if (aBoundingBoxType == LOOSE_INK_EXTENTS &&
         mAntialiasOption != kAntialiasNone &&
--- a/gfx/thebes/gfxDWriteFonts.h
+++ b/gfx/thebes/gfxDWriteFonts.h
@@ -45,17 +45,17 @@ public:
     }
 
     IDWriteFontFace *GetFontFace();
 
     /* override Measure to add padding for antialiasing */
     virtual RunMetrics Measure(gfxTextRun *aTextRun,
                                uint32_t aStart, uint32_t aEnd,
                                BoundingBoxType aBoundingBoxType,
-                               gfxContext *aContextForTightBoundingBox,
+                               DrawTarget *aDrawTargetForTightBoundingBox,
                                Spacing *aSpacing,
                                uint16_t aOrientation) override;
 
     virtual bool ProvidesGlyphWidths() const override;
 
     virtual int32_t GetGlyphWidth(DrawTarget& aDrawTarget,
                                   uint16_t aGID) override;
 
--- a/gfx/thebes/gfxFT2Fonts.cpp
+++ b/gfx/thebes/gfxFT2Fonts.cpp
@@ -38,29 +38,29 @@
 #include "mozilla/Preferences.h"
 #include "mozilla/gfx/2D.h"
 
 /**
  * gfxFT2Font
  */
 
 bool
-gfxFT2Font::ShapeText(gfxContext     *aContext,
+gfxFT2Font::ShapeText(DrawTarget     *aDrawTarget,
                       const char16_t *aText,
                       uint32_t        aOffset,
                       uint32_t        aLength,
                       int32_t         aScript,
                       bool            aVertical,
                       gfxShapedText  *aShapedText)
 {
-    if (!gfxFont::ShapeText(aContext, aText, aOffset, aLength, aScript,
+    if (!gfxFont::ShapeText(aDrawTarget, aText, aOffset, aLength, aScript,
                             aVertical, aShapedText)) {
         // harfbuzz must have failed(?!), just render raw glyphs
         AddRange(aText, aOffset, aLength, aShapedText);
-        PostShapingFixup(aContext->GetDrawTarget(), aText, aOffset, aLength,
+        PostShapingFixup(aDrawTarget, aText, aOffset, aLength,
                          aVertical, aShapedText);
     }
 
     return true;
 }
 
 void
 gfxFT2Font::AddRange(const char16_t *aText, uint32_t aOffset,
--- a/gfx/thebes/gfxFT2Fonts.h
+++ b/gfx/thebes/gfxFT2Fonts.h
@@ -60,17 +60,17 @@ public: // new functions
                                         FontCacheSizes* aSizes) const;
 
 #ifdef USE_SKIA
     virtual already_AddRefed<mozilla::gfx::GlyphRenderingOptions>
         GetGlyphRenderingOptions(const TextRunDrawParams* aRunParams = nullptr) override;
 #endif
 
 protected:
-    virtual bool ShapeText(gfxContext      *aContext,
+    virtual bool ShapeText(DrawTarget      *aDrawTarget,
                            const char16_t *aText,
                            uint32_t         aOffset,
                            uint32_t         aLength,
                            int32_t          aScript,
                            bool             aVertical,
                            gfxShapedText   *aShapedText);
 
     void FillGlyphDataForChar(uint32_t ch, CachedGlyphData *gd);
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -858,23 +858,23 @@ gfxFont::~gfxFont()
     if (mGlyphChangeObservers) {
         for (auto it = mGlyphChangeObservers->Iter(); !it.Done(); it.Next()) {
             it.Get()->GetKey()->ForgetFont();
         }
     }
 }
 
 gfxFloat
-gfxFont::GetGlyphHAdvance(gfxContext *aCtx, uint16_t aGID)
+gfxFont::GetGlyphHAdvance(DrawTarget* aDrawTarget, uint16_t aGID)
 {
-    if (!SetupCairoFont(aCtx->GetDrawTarget())) {
+    if (!SetupCairoFont(aDrawTarget)) {
         return 0;
     }
     if (ProvidesGlyphWidths()) {
-        return GetGlyphWidth(*aCtx->GetDrawTarget(), aGID) / 65536.0;
+        return GetGlyphWidth(*aDrawTarget, aGID) / 65536.0;
     }
     if (mFUnitsConvFactor < 0.0f) {
         GetMetrics(eHorizontal);
     }
     NS_ASSERTION(mFUnitsConvFactor >= 0.0f,
                  "missing font unit conversion factor");
     if (!mHarfBuzzShaper) {
         mHarfBuzzShaper = new gfxHarfBuzzShaper(this);
@@ -2227,37 +2227,37 @@ UnionRange(gfxFloat aX, gfxFloat* aDestM
 static bool
 NeedsGlyphExtents(gfxFont *aFont, gfxTextRun *aTextRun)
 {
     return (aTextRun->GetFlags() & gfxTextRunFactory::TEXT_NEED_BOUNDING_BOX) ||
         aFont->GetFontEntry()->IsUserFont();
 }
 
 bool
-gfxFont::IsSpaceGlyphInvisible(gfxContext *aRefContext, gfxTextRun *aTextRun)
+gfxFont::IsSpaceGlyphInvisible(DrawTarget* aRefDrawTarget, gfxTextRun* aTextRun)
 {
     if (!mFontEntry->mSpaceGlyphIsInvisibleInitialized &&
         GetAdjustedSize() >= 1.0) {
         gfxGlyphExtents *extents =
             GetOrCreateGlyphExtents(aTextRun->GetAppUnitsPerDevUnit());
         gfxRect glyphExtents;
         mFontEntry->mSpaceGlyphIsInvisible =
-            extents->GetTightGlyphExtentsAppUnits(this, aRefContext,
+            extents->GetTightGlyphExtentsAppUnits(this, aRefDrawTarget,
                 GetSpaceGlyph(), &glyphExtents) &&
             glyphExtents.IsEmpty();
         mFontEntry->mSpaceGlyphIsInvisibleInitialized = true;
     }
     return mFontEntry->mSpaceGlyphIsInvisible;
 }
 
 gfxFont::RunMetrics
 gfxFont::Measure(gfxTextRun *aTextRun,
                  uint32_t aStart, uint32_t aEnd,
                  BoundingBoxType aBoundingBoxType,
-                 gfxContext *aRefContext,
+                 DrawTarget* aRefDrawTarget,
                  Spacing *aSpacing,
                  uint16_t aOrientation)
 {
     // If aBoundingBoxType is TIGHT_HINTED_OUTLINE_EXTENTS
     // and the underlying cairo font may be antialiased,
     // we need to create a copy in order to avoid getting cached extents.
     // This is only used by MathML layout at present.
     if (aBoundingBoxType == TIGHT_HINTED_OUTLINE_EXTENTS &&
@@ -2265,17 +2265,17 @@ gfxFont::Measure(gfxTextRun *aTextRun,
         if (!mNonAAFont) {
             mNonAAFont = CopyWithAntialiasOption(kAntialiasNone);
         }
         // if font subclass doesn't implement CopyWithAntialiasOption(),
         // it will return null and we'll proceed to use the existing font
         if (mNonAAFont) {
             return mNonAAFont->Measure(aTextRun, aStart, aEnd,
                                        TIGHT_HINTED_OUTLINE_EXTENTS,
-                                       aRefContext, aSpacing, aOrientation);
+                                       aRefDrawTarget, aSpacing, aOrientation);
         }
     }
 
     const int32_t appUnitsPerDevUnit = aTextRun->GetAppUnitsPerDevUnit();
     // Current position in appunits
     gfxFont::Orientation orientation =
         aOrientation == gfxTextRunFactory::TEXT_ORIENT_VERTICAL_UPRIGHT
         ? eVertical : eHorizontal;
@@ -2328,32 +2328,32 @@ gfxFont::Measure(gfxTextRun *aTextRun,
     bool allGlyphsInvisible = true;
     uint32_t i;
     for (i = aStart; i < aEnd; ++i) {
         const gfxTextRun::CompressedGlyph *glyphData = &charGlyphs[i];
         if (glyphData->IsSimpleGlyph()) {
             double advance = glyphData->GetSimpleAdvance();
             uint32_t glyphIndex = glyphData->GetSimpleGlyph();
             if (glyphIndex != spaceGlyph ||
-                !IsSpaceGlyphInvisible(aRefContext, aTextRun)) {
+                !IsSpaceGlyphInvisible(aRefDrawTarget, aTextRun)) {
                 allGlyphsInvisible = false;
             }
             // Only get the real glyph horizontal extent if we were asked
             // for the tight bounding box or we're in quality mode
             if ((aBoundingBoxType != LOOSE_INK_EXTENTS || needsGlyphExtents) &&
                 extents){
                 uint16_t extentsWidth = extents->GetContainedGlyphWidthAppUnits(glyphIndex);
                 if (extentsWidth != gfxGlyphExtents::INVALID_WIDTH &&
                     aBoundingBoxType == LOOSE_INK_EXTENTS) {
                     UnionRange(x, &advanceMin, &advanceMax);
                     UnionRange(x + direction*extentsWidth, &advanceMin, &advanceMax);
                 } else {
                     gfxRect glyphRect;
                     if (!extents->GetTightGlyphExtentsAppUnits(this,
-                            aRefContext, glyphIndex, &glyphRect)) {
+                            aRefDrawTarget, glyphIndex, &glyphRect)) {
                         glyphRect = gfxRect(0, metrics.mBoundingBox.Y(),
                             advance, metrics.mBoundingBox.Height());
                     }
                     if (orientation == eVertical) {
                         Swap(glyphRect.x, glyphRect.y);
                         Swap(glyphRect.width, glyphRect.height);
                     }
                     if (isRTL) {
@@ -2375,17 +2375,17 @@ gfxFont::Measure(gfxTextRun *aTextRun,
                 uint32_t j;
                 for (j = 0; j < glyphCount; ++j, ++details) {
                     uint32_t glyphIndex = details->mGlyphID;
                     gfxPoint glyphPt(x + details->mXOffset, details->mYOffset);
                     double advance = details->mAdvance;
                     gfxRect glyphRect;
                     if (glyphData->IsMissing() || !extents ||
                         !extents->GetTightGlyphExtentsAppUnits(this,
-                                aRefContext, glyphIndex, &glyphRect)) {
+                                aRefDrawTarget, glyphIndex, &glyphRect)) {
                         // We might have failed to get glyph extents due to
                         // OOM or something
                         glyphRect = gfxRect(0, -metrics.mAscent,
                             advance, metrics.mAscent + metrics.mDescent);
                     }
                     if (orientation == eVertical) {
                         Swap(glyphRect.x, glyphRect.y);
                         Swap(glyphRect.width, glyphRect.height);
@@ -2495,17 +2495,17 @@ IsBoundarySpace(char16_t aChar, char16_t
 #ifdef __GNUC__
 #define GFX_MAYBE_UNUSED __attribute__((unused))
 #else
 #define GFX_MAYBE_UNUSED
 #endif
 
 template<typename T>
 gfxShapedWord*
-gfxFont::GetShapedWord(gfxContext *aContext,
+gfxFont::GetShapedWord(DrawTarget *aDrawTarget,
                        const T    *aText,
                        uint32_t    aLength,
                        uint32_t    aHash,
                        int32_t     aRunScript,
                        bool        aVertical,
                        int32_t     aAppUnitsPerDevUnit,
                        uint32_t    aFlags,
                        gfxTextPerfMetrics *aTextPerf GFX_MAYBE_UNUSED)
@@ -2560,17 +2560,17 @@ gfxFont::GetShapedWord(gfxContext *aCont
                                                     aAppUnitsPerDevUnit,
                                                     aFlags);
     if (!sw) {
         NS_WARNING("failed to create gfxShapedWord - expect missing text");
         return nullptr;
     }
 
     DebugOnly<bool> ok =
-        ShapeText(aContext, aText, 0, aLength, aRunScript, aVertical, sw);
+        ShapeText(aDrawTarget, aText, 0, aLength, aRunScript, aVertical, sw);
 
     NS_WARN_IF_FALSE(ok, "failed to shape word - expect garbled text");
 
     return sw;
 }
 
 bool
 gfxFont::CacheHashEntry::KeyEquals(const KeyTypePointer aKey) const
@@ -2605,68 +2605,68 @@ gfxFont::CacheHashEntry::KeyEquals(const
     }
     NS_ASSERTION((aKey->mFlags & gfxTextRunFactory::TEXT_IS_8BIT) == 0 &&
                  !aKey->mTextIs8Bit, "didn't expect 8-bit text here");
     return (0 == memcmp(sw->TextUnicode(), aKey->mText.mDouble,
                         aKey->mLength * sizeof(char16_t)));
 }
 
 bool
-gfxFont::ShapeText(gfxContext    *aContext,
+gfxFont::ShapeText(DrawTarget    *aDrawTarget,
                    const uint8_t *aText,
                    uint32_t       aOffset,
                    uint32_t       aLength,
                    int32_t        aScript,
                    bool           aVertical,
                    gfxShapedText *aShapedText)
 {
     nsDependentCSubstring ascii((const char*)aText, aLength);
     nsAutoString utf16;
     AppendASCIItoUTF16(ascii, utf16);
     if (utf16.Length() != aLength) {
         return false;
     }
-    return ShapeText(aContext, utf16.BeginReading(), aOffset, aLength,
+    return ShapeText(aDrawTarget, utf16.BeginReading(), aOffset, aLength,
                      aScript, aVertical, aShapedText);
 }
 
 bool
-gfxFont::ShapeText(gfxContext      *aContext,
+gfxFont::ShapeText(DrawTarget      *aDrawTarget,
                    const char16_t *aText,
                    uint32_t         aOffset,
                    uint32_t         aLength,
                    int32_t          aScript,
                    bool             aVertical,
                    gfxShapedText   *aShapedText)
 {
     bool ok = false;
 
     // XXX Currently, we do all vertical shaping through harfbuzz.
     // Vertical graphite support may be wanted as a future enhancement.
     if (FontCanSupportGraphite() && !aVertical) {
         if (gfxPlatform::GetPlatform()->UseGraphiteShaping()) {
             if (!mGraphiteShaper) {
                 mGraphiteShaper = new gfxGraphiteShaper(this);
             }
-            ok = mGraphiteShaper->ShapeText(aContext, aText, aOffset, aLength,
+            ok = mGraphiteShaper->ShapeText(aDrawTarget, aText, aOffset, aLength,
                                             aScript, aVertical, aShapedText);
         }
     }
 
     if (!ok) {
         if (!mHarfBuzzShaper) {
             mHarfBuzzShaper = new gfxHarfBuzzShaper(this);
         }
-        ok = mHarfBuzzShaper->ShapeText(aContext, aText, aOffset, aLength,
+        ok = mHarfBuzzShaper->ShapeText(aDrawTarget, aText, aOffset, aLength,
                                         aScript, aVertical, aShapedText);
     }
 
     NS_WARN_IF_FALSE(ok, "shaper failed, expect scrambled or missing text");
 
-    PostShapingFixup(aContext->GetDrawTarget(), aText, aOffset, aLength,
+    PostShapingFixup(aDrawTarget, aText, aOffset, aLength,
                      aVertical, aShapedText);
 
     return ok;
 }
 
 void
 gfxFont::PostShapingFixup(DrawTarget*     aDrawTarget,
                           const char16_t* aText,
@@ -2689,17 +2689,17 @@ gfxFont::PostShapingFixup(DrawTarget*   
 
 #define MAX_SHAPING_LENGTH  32760 // slightly less than 32K, trying to avoid
                                   // over-stressing platform shapers
 #define BACKTRACK_LIMIT     16 // backtrack this far looking for a good place
                                // to split into fragments for separate shaping
 
 template<typename T>
 bool
-gfxFont::ShapeFragmentWithoutWordCache(gfxContext *aContext,
+gfxFont::ShapeFragmentWithoutWordCache(DrawTarget *aDrawTarget,
                                        const T    *aText,
                                        uint32_t    aOffset,
                                        uint32_t    aLength,
                                        int32_t     aScript,
                                        bool        aVertical,
                                        gfxTextRun *aTextRun)
 {
     aTextRun->SetupClusterBoundaries(aOffset, aText, aLength);
@@ -2730,17 +2730,17 @@ gfxFont::ShapeFragmentWithoutWordCache(g
                     if (NS_IS_LOW_SURROGATE(aText[fragLen]) &&
                         NS_IS_HIGH_SURROGATE(aText[fragLen - 1])) {
                         --fragLen;
                     }
                 }
             }
         }
 
-        ok = ShapeText(aContext, aText, aOffset, fragLen, aScript, aVertical,
+        ok = ShapeText(aDrawTarget, aText, aOffset, fragLen, aScript, aVertical,
                        aTextRun);
 
         aText += fragLen;
         aOffset += fragLen;
         aLength -= fragLen;
     }
 
     return ok;
@@ -2754,17 +2754,17 @@ gfxFont::ShapeFragmentWithoutWordCache(g
 static bool
 IsInvalidControlChar(uint32_t aCh)
 {
     return aCh != '\r' && ((aCh & 0x7f) < 0x20 || aCh == 0x7f);
 }
 
 template<typename T>
 bool
-gfxFont::ShapeTextWithoutWordCache(gfxContext *aContext,
+gfxFont::ShapeTextWithoutWordCache(DrawTarget *aDrawTarget,
                                    const T    *aText,
                                    uint32_t    aOffset,
                                    uint32_t    aLength,
                                    int32_t     aScript,
                                    bool        aVertical,
                                    gfxTextRun *aTextRun)
 {
     uint32_t fragStart = 0;
@@ -2776,17 +2776,17 @@ gfxFont::ShapeTextWithoutWordCache(gfxCo
         uint32_t length = i - fragStart;
 
         // break into separate fragments when we hit an invalid char
         if (!invalid) {
             continue;
         }
 
         if (length > 0) {
-            ok = ShapeFragmentWithoutWordCache(aContext, aText + fragStart,
+            ok = ShapeFragmentWithoutWordCache(aDrawTarget, aText + fragStart,
                                                aOffset + fragStart, length,
                                                aScript, aVertical, aTextRun);
         }
 
         if (i == aLength) {
             break;
         }
 
@@ -2795,17 +2795,17 @@ gfxFont::ShapeTextWithoutWordCache(gfxCo
         // but record where TAB or NEWLINE occur
         if (ch == '\t') {
             aTextRun->SetIsTab(aOffset + i);
         } else if (ch == '\n') {
             aTextRun->SetIsNewline(aOffset + i);
         } else if (IsInvalidControlChar(ch) &&
             !(aTextRun->GetFlags() & gfxTextRunFactory::TEXT_HIDE_CONTROL_CHARACTERS)) {
             if (GetFontEntry()->IsUserFont() && HasCharacter(ch)) {
-                ShapeFragmentWithoutWordCache(aContext, aText + i,
+                ShapeFragmentWithoutWordCache(aDrawTarget, aText + i,
                                               aOffset + i, 1,
                                               aScript, aVertical, aTextRun);
             } else {
                 aTextRun->SetMissingGlyph(aOffset + i, ch, this);
             }
         }
         fragStart = i + 1;
     }
@@ -2835,17 +2835,17 @@ inline static bool HasSpaces(const char1
             return true;
         }
     }
     return false;
 }
 
 template<typename T>
 bool
-gfxFont::SplitAndInitTextRun(gfxContext *aContext,
+gfxFont::SplitAndInitTextRun(DrawTarget *aDrawTarget,
                              gfxTextRun *aTextRun,
                              const T *aString, // text for this font run
                              uint32_t aRunStart, // position in the textrun
                              uint32_t aRunLength,
                              int32_t aRunScript,
                              bool aVertical)
 {
     if (aRunLength == 0) {
@@ -2875,17 +2875,17 @@ gfxFont::SplitAndInitTextRun(gfxContext 
     // If spaces can participate in shaping (e.g. within lookups for automatic
     // fractions), need to shape without using the word cache which segments
     // textruns on space boundaries. Word cache can be used if the textrun
     // is short enough to fit in the word cache and it lacks spaces.
     if (SpaceMayParticipateInShaping(aRunScript)) {
         if (aRunLength > wordCacheCharLimit ||
             HasSpaces(aString, aRunLength)) {
             TEXT_PERF_INCR(tp, wordCacheSpaceRules);
-            return ShapeTextWithoutWordCache(aContext, aString,
+            return ShapeTextWithoutWordCache(aDrawTarget, aString,
                                              aRunStart, aRunLength,
                                              aRunScript, aVertical,
                                              aTextRun);
         }
     }
 
     InitWordCache();
 
@@ -2925,17 +2925,17 @@ gfxFont::SplitAndInitTextRun(gfxContext 
         }
 
         // We've decided to break here (i.e. we're at the end of a "word");
         // shape the word and add it to the textrun.
         // For words longer than the limit, we don't use the
         // font's word cache but just shape directly into the textrun.
         if (length > wordCacheCharLimit) {
             TEXT_PERF_INCR(tp, wordCacheLong);
-            bool ok = ShapeFragmentWithoutWordCache(aContext,
+            bool ok = ShapeFragmentWithoutWordCache(aDrawTarget,
                                                     aString + wordStart,
                                                     aRunStart + wordStart,
                                                     length,
                                                     aRunScript,
                                                     aVertical,
                                                     aTextRun);
             if (!ok) {
                 return false;
@@ -2945,17 +2945,17 @@ gfxFont::SplitAndInitTextRun(gfxContext 
             // in the 8-bit version of this method, TEXT_IS_8BIT was
             // already set as part of |flags|, so no need for a per-word
             // adjustment here
             if (sizeof(T) == sizeof(char16_t)) {
                 if (wordIs8Bit) {
                     wordFlags |= gfxTextRunFactory::TEXT_IS_8BIT;
                 }
             }
-            gfxShapedWord *sw = GetShapedWord(aContext,
+            gfxShapedWord* sw = GetShapedWord(aDrawTarget,
                                               aString + wordStart, length,
                                               hash, aRunScript, aVertical,
                                               appUnitsPerDevUnit,
                                               wordFlags, tp);
             if (sw) {
                 aTextRun->CopyGlyphDataFrom(sw, aRunStart + wordStart);
             } else {
                 return false; // failed, presumably out of memory?
@@ -2976,17 +2976,17 @@ gfxFont::SplitAndInitTextRun(gfxContext 
                 // Currently, the only "boundary" characters we recognize are
                 // space and no-break space, which are both 8-bit, so we force
                 // that flag (below). If we ever change IsBoundarySpace, we
                 // may need to revise this.
                 // Avoid tautological-constant-out-of-range-compare in 8-bit:
                 DebugOnly<char16_t> boundary16 = boundary;
                 NS_ASSERTION(boundary16 < 256, "unexpected boundary!");
                 gfxShapedWord *sw =
-                    GetShapedWord(aContext, &boundary, 1,
+                    GetShapedWord(aDrawTarget, &boundary, 1,
                                   gfxShapedWord::HashMix(0, boundary),
                                   aRunScript, aVertical, appUnitsPerDevUnit,
                                   flags | gfxTextRunFactory::TEXT_IS_8BIT, tp);
                 if (sw) {
                     aTextRun->CopyGlyphDataFrom(sw, aRunStart + i);
                 } else {
                     return false;
                 }
@@ -3009,17 +3009,17 @@ gfxFont::SplitAndInitTextRun(gfxContext 
         // but record where TAB or NEWLINE occur
         if (ch == '\t') {
             aTextRun->SetIsTab(aRunStart + i);
         } else if (ch == '\n') {
             aTextRun->SetIsNewline(aRunStart + i);
         } else if (IsInvalidControlChar(ch) &&
             !(aTextRun->GetFlags() & gfxTextRunFactory::TEXT_HIDE_CONTROL_CHARACTERS)) {
             if (GetFontEntry()->IsUserFont() && HasCharacter(ch)) {
-                ShapeFragmentWithoutWordCache(aContext, aString + i,
+                ShapeFragmentWithoutWordCache(aDrawTarget, aString + i,
                                               aRunStart + i, 1,
                                               aRunScript, aVertical, aTextRun);
             } else {
                 aTextRun->SetMissingGlyph(aRunStart + i, ch, this);
             }
         }
 
         hash = 0;
@@ -3027,35 +3027,35 @@ gfxFont::SplitAndInitTextRun(gfxContext 
         wordIs8Bit = true;
     }
 
     return true;
 }
 
 // Explicit instantiations of SplitAndInitTextRun, to avoid libxul link failure
 template bool
-gfxFont::SplitAndInitTextRun(gfxContext *aContext,
+gfxFont::SplitAndInitTextRun(DrawTarget *aDrawTarget,
                              gfxTextRun *aTextRun,
                              const uint8_t *aString,
                              uint32_t aRunStart,
                              uint32_t aRunLength,
                              int32_t aRunScript,
                              bool aVertical);
 template bool
-gfxFont::SplitAndInitTextRun(gfxContext *aContext,
+gfxFont::SplitAndInitTextRun(DrawTarget *aDrawTarget,
                              gfxTextRun *aTextRun,
                              const char16_t *aString,
                              uint32_t aRunStart,
                              uint32_t aRunLength,
                              int32_t aRunScript,
                              bool aVertical);
 
 template<>
 bool
-gfxFont::InitFakeSmallCapsRun(gfxContext     *aContext,
+gfxFont::InitFakeSmallCapsRun(DrawTarget     *aDrawTarget,
                               gfxTextRun     *aTextRun,
                               const char16_t *aText,
                               uint32_t        aOffset,
                               uint32_t        aLength,
                               uint8_t         aMatchType,
                               uint16_t        aOrientation,
                               int32_t         aScript,
                               bool            aSyntheticLower,
@@ -3126,17 +3126,17 @@ gfxFont::InitFakeSmallCapsRun(gfxContext
         if ((i == aLength || runAction != chAction) && runStart < i) {
             uint32_t runLength = i - runStart;
             gfxFont* f = this;
             switch (runAction) {
             case kNoChange:
                 // just use the current font and the existing string
                 aTextRun->AddGlyphRun(f, aMatchType, aOffset + runStart, true,
                                       aOrientation);
-                if (!f->SplitAndInitTextRun(aContext, aTextRun,
+                if (!f->SplitAndInitTextRun(aDrawTarget, aTextRun,
                                             aText + runStart,
                                             aOffset + runStart, runLength,
                                             aScript, vertical)) {
                     ok = false;
                 }
                 break;
 
             case kUppercaseReduce:
@@ -3161,25 +3161,25 @@ gfxFont::InitFakeSmallCapsRun(gfxContext
                                     deletedCharsArray);
 
                 if (mergeNeeded) {
                     // This is the hard case: the transformation caused chars
                     // to be inserted or deleted, so we can't shape directly
                     // into the destination textrun but have to handle the
                     // mismatch of character positions.
                     gfxTextRunFactory::Parameters params = {
-                        aContext, nullptr, nullptr, nullptr, 0,
+                        aDrawTarget, nullptr, nullptr, nullptr, 0,
                         aTextRun->GetAppUnitsPerDevUnit()
                     };
                     nsAutoPtr<gfxTextRun> tempRun;
                     tempRun =
                         gfxTextRun::Create(&params, convertedString.Length(),
                                            aTextRun->GetFontGroup(), 0);
                     tempRun->AddGlyphRun(f, aMatchType, 0, true, aOrientation);
-                    if (!f->SplitAndInitTextRun(aContext, tempRun,
+                    if (!f->SplitAndInitTextRun(aDrawTarget, tempRun,
                                                 convertedString.BeginReading(),
                                                 0, convertedString.Length(),
                                                 aScript, vertical)) {
                         ok = false;
                     } else {
                         nsAutoPtr<gfxTextRun> mergedRun;
                         mergedRun =
                             gfxTextRun::Create(&params, runLength,
@@ -3188,17 +3188,17 @@ gfxFont::InitFakeSmallCapsRun(gfxContext
                                                  charsToMergeArray.Elements(),
                                                  deletedCharsArray.Elements());
                         aTextRun->CopyGlyphDataFrom(mergedRun, 0, runLength,
                                                     aOffset + runStart);
                     }
                 } else {
                     aTextRun->AddGlyphRun(f, aMatchType, aOffset + runStart,
                                           true, aOrientation);
-                    if (!f->SplitAndInitTextRun(aContext, aTextRun,
+                    if (!f->SplitAndInitTextRun(aDrawTarget, aTextRun,
                                                 convertedString.BeginReading(),
                                                 aOffset + runStart, runLength,
                                                 aScript, vertical)) {
                         ok = false;
                     }
                 }
                 break;
             }
@@ -3212,30 +3212,30 @@ gfxFont::InitFakeSmallCapsRun(gfxContext
         }
     }
 
     return ok;
 }
 
 template<>
 bool
-gfxFont::InitFakeSmallCapsRun(gfxContext     *aContext,
+gfxFont::InitFakeSmallCapsRun(DrawTarget     *aDrawTarget,
                               gfxTextRun     *aTextRun,
                               const uint8_t  *aText,
                               uint32_t        aOffset,
                               uint32_t        aLength,
                               uint8_t         aMatchType,
                               uint16_t        aOrientation,
                               int32_t         aScript,
                               bool            aSyntheticLower,
                               bool            aSyntheticUpper)
 {
     NS_ConvertASCIItoUTF16 unicodeString(reinterpret_cast<const char*>(aText),
                                          aLength);
-    return InitFakeSmallCapsRun(aContext, aTextRun, static_cast<const char16_t*>(unicodeString.get()),
+    return InitFakeSmallCapsRun(aDrawTarget, aTextRun, static_cast<const char16_t*>(unicodeString.get()),
                                 aOffset, aLength, aMatchType, aOrientation,
                                 aScript, aSyntheticLower, aSyntheticUpper);
 }
 
 already_AddRefed<gfxFont>
 gfxFont::GetSmallCapsFont()
 {
     gfxFontStyle style(*GetStyle());
--- a/gfx/thebes/gfxFont.h
+++ b/gfx/thebes/gfxFont.h
@@ -449,16 +449,18 @@ public:
         memset(&current, 0, sizeof(current));
     }
 };
 
 class gfxTextRunFactory {
     NS_INLINE_DECL_REFCOUNTING(gfxTextRunFactory)
 
 public:
+    typedef mozilla::gfx::DrawTarget DrawTarget;
+
     // Flags in the mask 0xFFFF0000 are reserved for textrun clients
     // Flags in the mask 0x0000F000 are reserved for per-platform fonts
     // Flags in the mask 0x00000FFF are set by the textrun creator.
     enum {
         CACHE_TEXT_FLAGS    = 0xF0000000,
         USER_TEXT_FLAGS     = 0x0FFF0000,
         TEXTRUN_TEXT_FLAGS  = 0x0000FFFF,
         SETTABLE_FLAGS      = CACHE_TEXT_FLAGS | USER_TEXT_FLAGS,
@@ -567,18 +569,18 @@ public:
 
         TEXT_UNUSED_FLAGS = 0x10000000
     };
 
     /**
      * This record contains all the parameters needed to initialize a textrun.
      */
     struct Parameters {
-        // A reference context suggesting where the textrun will be rendered
-        gfxContext   *mContext;
+        // Shape text params suggesting where the textrun will be rendered
+        DrawTarget   *mDrawTarget;
         // Pointer to arbitrary user data (which should outlive the textrun)
         void         *mUserData;
         // A description of which characters have been stripped from the original
         // DOM string to produce the characters in the textrun. May be null
         // if that information is not relevant.
         gfxSkipChars *mSkipChars;
         // A list of where linebreaks are currently placed in the textrun. May
         // be null if mInitialBreakCount is zero.
@@ -621,17 +623,17 @@ public:
         NS_ASSERTION(aFont, "shaper requires a valid font!");
     }
 
     virtual ~gfxFontShaper() { }
 
     // Shape a piece of text and store the resulting glyph data into
     // aShapedText. Parameters aOffset/aLength indicate the range of
     // aShapedText to be updated; aLength is also the length of aText.
-    virtual bool ShapeText(gfxContext     *aContext,
+    virtual bool ShapeText(DrawTarget     *aDrawTarget,
                            const char16_t *aText,
                            uint32_t        aOffset,
                            uint32_t        aLength,
                            int32_t         aScript,
                            bool            aVertical,
                            gfxShapedText  *aShapedText) = 0;
 
     gfxFont *GetFont() const { return mFont; }
@@ -1481,17 +1483,17 @@ public:
         return false;
     }
     // Map unicode character to glyph ID.
     // Only used if ProvidesGetGlyph() returns true.
     virtual uint32_t GetGlyph(uint32_t unicode, uint32_t variation_selector) {
         return 0;
     }
     // Return the horizontal advance of a glyph.
-    gfxFloat GetGlyphHAdvance(gfxContext *aCtx, uint16_t aGID);
+    gfxFloat GetGlyphHAdvance(DrawTarget* aDrawTarget, uint16_t aGID);
 
     // Return Azure GlyphRenderingOptions for drawing this font.
     virtual already_AddRefed<mozilla::gfx::GlyphRenderingOptions>
       GetGlyphRenderingOptions(const TextRunDrawParams* aRunParams = nullptr)
     { return nullptr; }
 
     gfxFloat SynthesizeSpaceWidth(uint32_t aCh);
 
@@ -1621,34 +1623,34 @@ public:
 
     /**
      * Measure a run of characters. See gfxTextRun::Metrics.
      * @param aTight if false, then return the union of the glyph extents
      * with the font-box for the characters (the rectangle with x=0,width=
      * the advance width for the character run,y=-(font ascent), and height=
      * font ascent + font descent). Otherwise, we must return as tight as possible
      * an approximation to the area actually painted by glyphs.
-     * @param aContextForTightBoundingBox when aTight is true, this must
+     * @param aDrawTargetForTightBoundingBox when aTight is true, this must
      * be non-null.
      * @param aSpacing spacing to insert before and after glyphs. The bounding box
      * need not include the spacing itself, but the spacing affects the glyph
      * positions. null if there is no spacing.
      * 
      * Callers guarantee:
      * -- aStart and aEnd are aligned to cluster and ligature boundaries
      * -- all glyphs use this font
      * 
      * The default implementation just uses font metrics and aTextRun's
      * advances, and assumes no characters fall outside the font box. In
      * general this is insufficient, because that assumption is not always true.
      */
     virtual RunMetrics Measure(gfxTextRun *aTextRun,
                                uint32_t aStart, uint32_t aEnd,
                                BoundingBoxType aBoundingBoxType,
-                               gfxContext *aContextForTightBoundingBox,
+                               DrawTarget* aDrawTargetForTightBoundingBox,
                                Spacing *aSpacing, uint16_t aOrientation);
     /**
      * Line breaks have been changed at the beginning and/or end of a substring
      * of the text. Reshaping may be required; glyph updating is permitted.
      * @return true if anything was changed, false otherwise
      */
     bool NotifyLineBreaksChanged(gfxTextRun *aTextRun,
                                    uint32_t aStart, uint32_t aLength)
@@ -1704,43 +1706,43 @@ public:
     uint16_t GetUVSGlyph(uint32_t aCh, uint32_t aVS) {
         if (!mIsValid) {
             return 0;
         }
         return mFontEntry->GetUVSGlyph(aCh, aVS); 
     }
 
     template<typename T>
-    bool InitFakeSmallCapsRun(gfxContext *aContext,
+    bool InitFakeSmallCapsRun(DrawTarget *aDrawTarget,
                               gfxTextRun *aTextRun,
                               const T    *aText,
                               uint32_t    aOffset,
                               uint32_t    aLength,
                               uint8_t     aMatchType,
                               uint16_t    aOrientation,
                               int32_t     aScript,
                               bool        aSyntheticLower,
                               bool        aSyntheticUpper);
 
     // call the (virtual) InitTextRun method to do glyph generation/shaping,
     // limiting the length of text passed by processing the run in multiple
     // segments if necessary
     template<typename T>
-    bool SplitAndInitTextRun(gfxContext *aContext,
+    bool SplitAndInitTextRun(DrawTarget *aDrawTarget,
                              gfxTextRun *aTextRun,
                              const T *aString,
                              uint32_t aRunStart,
                              uint32_t aRunLength,
                              int32_t aRunScript,
                              bool aVertical);
 
     // Get a ShapedWord representing the given text (either 8- or 16-bit)
     // for use in setting up a gfxTextRun.
     template<typename T>
-    gfxShapedWord* GetShapedWord(gfxContext *aContext,
+    gfxShapedWord* GetShapedWord(DrawTarget *aDrawTarget,
                                  const T *aText,
                                  uint32_t aLength,
                                  uint32_t aHash,
                                  int32_t aRunScript,
                                  bool aVertical,
                                  int32_t aAppUnitsPerDevUnit,
                                  uint32_t aFlags,
                                  gfxTextPerfMetrics *aTextPerf);
@@ -1900,39 +1902,40 @@ protected:
     }
 
     // The return value is interpreted as a horizontal advance in 16.16 fixed
     // point format.
     virtual int32_t GetGlyphWidth(DrawTarget& aDrawTarget, uint16_t aGID) {
         return -1;
     }
 
-    bool IsSpaceGlyphInvisible(gfxContext *aRefContext, gfxTextRun *aTextRun);
+    bool IsSpaceGlyphInvisible(DrawTarget* aRefDrawTarget,
+                               gfxTextRun* aTextRun);
 
     void AddGlyphChangeObserver(GlyphChangeObserver *aObserver);
     void RemoveGlyphChangeObserver(GlyphChangeObserver *aObserver);
 
     // whether font contains substitution lookups containing spaces
     bool HasSubstitutionRulesWithSpaceLookups(int32_t aRunScript);
 
     // do spaces participate in shaping rules? if so, can't used word cache
     bool SpaceMayParticipateInShaping(int32_t aRunScript);
 
     // For 8-bit text, expand to 16-bit and then call the following method.
-    bool ShapeText(gfxContext    *aContext,
+    bool ShapeText(DrawTarget    *aContext,
                    const uint8_t *aText,
                    uint32_t       aOffset, // dest offset in gfxShapedText
                    uint32_t       aLength,
                    int32_t        aScript,
                    bool           aVertical,
                    gfxShapedText *aShapedText); // where to store the result
 
     // Call the appropriate shaper to generate glyphs for aText and store
     // them into aShapedText.
-    virtual bool ShapeText(gfxContext      *aContext,
+    virtual bool ShapeText(DrawTarget      *aContext,
                            const char16_t *aText,
                            uint32_t         aOffset,
                            uint32_t         aLength,
                            int32_t          aScript,
                            bool             aVertical,
                            gfxShapedText   *aShapedText);
 
     // Helper to adjust for synthetic bold and set character-type flags
@@ -1948,31 +1951,31 @@ protected:
     // Shape text directly into a range within a textrun, without using the
     // font's word cache. Intended for use when the font has layout features
     // that involve space, and therefore require shaping complete runs rather
     // than isolated words, or for long strings that are inefficient to cache.
     // This will split the text on "invalid" characters (tab/newline) that are
     // not handled via normal shaping, but does not otherwise divide up the
     // text.
     template<typename T>
-    bool ShapeTextWithoutWordCache(gfxContext *aContext,
+    bool ShapeTextWithoutWordCache(DrawTarget *aDrawTarget,
                                    const T    *aText,
                                    uint32_t    aOffset,
                                    uint32_t    aLength,
                                    int32_t     aScript,
                                    bool        aVertical,
                                    gfxTextRun *aTextRun);
 
     // Shape a fragment of text (a run that is known to contain only
     // "valid" characters, no newlines/tabs/other control chars).
     // All non-wordcache shaping goes through here; this is the function
     // that will ensure we don't pass excessively long runs to the various
     // platform shapers.
     template<typename T>
-    bool ShapeFragmentWithoutWordCache(gfxContext *aContext,
+    bool ShapeFragmentWithoutWordCache(DrawTarget *aDrawTarget,
                                        const T    *aText,
                                        uint32_t    aOffset,
                                        uint32_t    aLength,
                                        int32_t     aScript,
                                        bool        aVertical,
                                        gfxTextRun *aTextRun);
 
     void CheckForFeaturesInvolvingSpace();
--- a/gfx/thebes/gfxGDIFont.cpp
+++ b/gfx/thebes/gfxGDIFont.cpp
@@ -73,17 +73,17 @@ gfxGDIFont::~gfxGDIFont()
 gfxFont*
 gfxGDIFont::CopyWithAntialiasOption(AntialiasOption anAAOption)
 {
     return new gfxGDIFont(static_cast<GDIFontEntry*>(mFontEntry.get()),
                           &mStyle, mNeedsBold, anAAOption);
 }
 
 bool
-gfxGDIFont::ShapeText(gfxContext     *aContext,
+gfxGDIFont::ShapeText(DrawTarget     *aDrawTarget,
                       const char16_t *aText,
                       uint32_t        aOffset,
                       uint32_t        aLength,
                       int32_t         aScript,
                       bool            aVertical,
                       gfxShapedText  *aShapedText)
 {
     if (!mMetrics) {
@@ -93,21 +93,21 @@ gfxGDIFont::ShapeText(gfxContext     *aC
         NS_WARNING("invalid font! expect incorrect text rendering");
         return false;
     }
 
     // Ensure the cairo font is set up, so there's no risk it'll fall back to
     // creating a "toy" font internally (see bug 544617).
     // We must check that this succeeded, otherwise we risk cairo creating the
     // wrong kind of font internally as a fallback (bug 744480).
-    if (!SetupCairoFont(aContext->GetDrawTarget())) {
+    if (!SetupCairoFont(aDrawTarget)) {
         return false;
     }
 
-    return gfxFont::ShapeText(aContext, aText, aOffset, aLength, aScript,
+    return gfxFont::ShapeText(aDrawTarget, aText, aOffset, aLength, aScript,
                               aVertical, aShapedText);
 }
 
 const gfxFont::Metrics&
 gfxGDIFont::GetHorizontalMetrics()
 {
     if (!mMetrics) {
         Initialize();
@@ -139,24 +139,23 @@ gfxGDIFont::SetupCairoFont(DrawTarget* a
     cairo_set_scaled_font(gfxFont::RefCairo(aDrawTarget), mScaledFont);
     return true;
 }
 
 gfxFont::RunMetrics
 gfxGDIFont::Measure(gfxTextRun *aTextRun,
                     uint32_t aStart, uint32_t aEnd,
                     BoundingBoxType aBoundingBoxType,
-                    gfxContext *aRefContext,
+                    DrawTarget *aRefDrawTarget,
                     Spacing *aSpacing,
                     uint16_t aOrientation)
 {
     gfxFont::RunMetrics metrics =
-        gfxFont::Measure(aTextRun, aStart, aEnd,
-                         aBoundingBoxType, aRefContext, aSpacing,
-                         aOrientation);
+        gfxFont::Measure(aTextRun, aStart, aEnd, aBoundingBoxType,
+                         aRefDrawTarget, aSpacing, aOrientation);
 
     // if aBoundingBoxType is LOOSE_INK_EXTENTS
     // and the underlying cairo font may be antialiased,
     // we can't trust Windows to have considered all the pixels
     // so we need to add "padding" to the bounds.
     // (see bugs 475968, 439831, compare also bug 445087)
     if (aBoundingBoxType == LOOSE_INK_EXTENTS &&
         mAntialiasOption != kAntialiasNone &&
--- a/gfx/thebes/gfxGDIFont.h
+++ b/gfx/thebes/gfxGDIFont.h
@@ -43,17 +43,17 @@ public:
     virtual uint32_t GetSpaceGlyph() override;
 
     virtual bool SetupCairoFont(DrawTarget* aDrawTarget) override;
 
     /* override Measure to add padding for antialiasing */
     virtual RunMetrics Measure(gfxTextRun *aTextRun,
                                uint32_t aStart, uint32_t aEnd,
                                BoundingBoxType aBoundingBoxType,
-                               gfxContext *aContextForTightBoundingBox,
+                               DrawTarget *aDrawTargetForTightBoundingBox,
                                Spacing *aSpacing,
                                uint16_t aOrientation) override;
 
     /* required for MathML to suppress effects of ClearType "padding" */
     virtual gfxFont*
     CopyWithAntialiasOption(AntialiasOption anAAOption) override;
 
     // If the font has a cmap table, we handle it purely with harfbuzz;
@@ -77,17 +77,17 @@ public:
                                         FontCacheSizes* aSizes) const;
 
     virtual FontType GetType() const override { return FONT_TYPE_GDI; }
 
 protected:
     virtual const Metrics& GetHorizontalMetrics() override;
 
     /* override to ensure the cairo font is set up properly */
-    virtual bool ShapeText(gfxContext     *aContext,
+    virtual bool ShapeText(DrawTarget     *aDrawTarget,
                            const char16_t *aText,
                            uint32_t        aOffset,
                            uint32_t        aLength,
                            int32_t         aScript,
                            bool            aVertical,
                            gfxShapedText  *aShapedText) override;
 
     void Initialize(); // creates metrics and Cairo fonts
--- a/gfx/thebes/gfxGlyphExtents.cpp
+++ b/gfx/thebes/gfxGlyphExtents.cpp
@@ -30,31 +30,34 @@ gfxGlyphExtents::~gfxGlyphExtents()
     gGlyphExtentsWidthsTotalSize +=
         mContainedGlyphWidths.SizeOfExcludingThis(&FontCacheMallocSizeOf);
     gGlyphExtentsCount++;
 #endif
     MOZ_COUNT_DTOR(gfxGlyphExtents);
 }
 
 bool
-gfxGlyphExtents::GetTightGlyphExtentsAppUnits(gfxFont *aFont,
-    gfxContext *aContext, uint32_t aGlyphID, gfxRect *aExtents)
+gfxGlyphExtents::GetTightGlyphExtentsAppUnits(gfxFont* aFont,
+    DrawTarget* aDrawTarget, uint32_t aGlyphID, gfxRect* aExtents)
 {
     HashEntry *entry = mTightGlyphExtents.GetEntry(aGlyphID);
     if (!entry) {
-        if (!aContext) {
-            NS_WARNING("Could not get glyph extents (no aContext)");
+        // Some functions higher up in the call chain deliberately pass in a
+        // nullptr DrawTarget, e.g. GetBaselinePosition() passes nullptr to
+        // gfxTextRun::MeasureText() and that nullptr reaches here.
+        if (!aDrawTarget) {
+            NS_WARNING("Could not get glyph extents (no aDrawTarget)");
             return false;
         }
 
-        if (aFont->SetupCairoFont(aContext->GetDrawTarget())) {
+        if (aFont->SetupCairoFont(aDrawTarget)) {
 #ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
             ++gGlyphExtentsSetupLazyTight;
 #endif
-            aFont->SetupGlyphExtents(aContext->GetDrawTarget(), aGlyphID, true, this);
+            aFont->SetupGlyphExtents(aDrawTarget, aGlyphID, true, this);
             entry = mTightGlyphExtents.GetEntry(aGlyphID);
         }
         if (!entry) {
             NS_WARNING("Could not get glyph extents");
             return false;
         }
     }
 
--- a/gfx/thebes/gfxGlyphExtents.h
+++ b/gfx/thebes/gfxGlyphExtents.h
@@ -57,18 +57,18 @@ public:
 
     bool IsGlyphKnownWithTightExtents(uint32_t aGlyphID) const {
         return mTightGlyphExtents.GetEntry(aGlyphID) != nullptr;
     }
 
     // Get glyph extents; a rectangle relative to the left baseline origin
     // Returns true on success. Can fail on OOM or when aContext is null
     // and extents were not (successfully) prefetched.
-    bool GetTightGlyphExtentsAppUnits(gfxFont *aFont,
-            gfxContext *aContext, uint32_t aGlyphID, gfxRect *aExtents);
+    bool GetTightGlyphExtentsAppUnits(gfxFont* aFont,
+            DrawTarget* aDrawTarget, uint32_t aGlyphID, gfxRect* aExtents);
 
     void SetContainedGlyphWidthAppUnits(uint32_t aGlyphID, uint16_t aWidth) {
         mContainedGlyphWidths.Set(aGlyphID, aWidth);
     }
     void SetTightGlyphExtents(uint32_t aGlyphID, const gfxRect& aExtentsAppUnits);
 
     int32_t GetAppUnitsPerDevUnit() { return mAppUnitsPerDevUnit; }
 
--- a/gfx/thebes/gfxGraphiteShaper.cpp
+++ b/gfx/thebes/gfxGraphiteShaper.cpp
@@ -77,30 +77,30 @@ AddFeature(const uint32_t& aTag, uint32_
 
     const gr_feature_ref* fref = gr_face_find_fref(f->mFace, aTag);
     if (fref) {
         gr_fref_set_feature_value(fref, aValue, f->mFeatures);
     }
 }
 
 bool
-gfxGraphiteShaper::ShapeText(gfxContext      *aContext,
+gfxGraphiteShaper::ShapeText(DrawTarget      *aDrawTarget,
                              const char16_t *aText,
                              uint32_t         aOffset,
                              uint32_t         aLength,
                              int32_t          aScript,
                              bool             aVertical,
                              gfxShapedText   *aShapedText)
 {
     // some font back-ends require this in order to get proper hinted metrics
-    if (!mFont->SetupCairoFont(aContext->GetDrawTarget())) {
+    if (!mFont->SetupCairoFont(aDrawTarget)) {
         return false;
     }
 
-    mCallbackData.mDrawTarget = aContext->GetDrawTarget();
+    mCallbackData.mDrawTarget = aDrawTarget;
 
     const gfxFontStyle *style = mFont->GetStyle();
 
     if (!mGrFont) {
         if (!mGrFace) {
             return false;
         }
 
@@ -168,17 +168,17 @@ gfxGraphiteShaper::ShapeText(gfxContext 
                                   gr_utf16, aText, numChars, grBidi);
 
     gr_featureval_destroy(grFeatures);
 
     if (!seg) {
         return false;
     }
 
-    nsresult rv = SetGlyphsFromSegment(aContext, aShapedText, aOffset, aLength,
+    nsresult rv = SetGlyphsFromSegment(aDrawTarget, aShapedText, aOffset, aLength,
                                        aText, seg);
 
     gr_seg_destroy(seg);
 
     return NS_SUCCEEDED(rv);
 }
 
 #define SMALL_GLYPH_RUN 256 // avoid heap allocation of per-glyph data arrays
@@ -188,17 +188,17 @@ struct Cluster {
     uint32_t baseChar; // in UTF16 code units, not Unicode character indices
     uint32_t baseGlyph;
     uint32_t nChars; // UTF16 code units
     uint32_t nGlyphs;
     Cluster() : baseChar(0), baseGlyph(0), nChars(0), nGlyphs(0) { }
 };
 
 nsresult
-gfxGraphiteShaper::SetGlyphsFromSegment(gfxContext      *aContext,
+gfxGraphiteShaper::SetGlyphsFromSegment(DrawTarget      *aDrawTarget,
                                         gfxShapedText   *aShapedText,
                                         uint32_t         aOffset,
                                         uint32_t         aLength,
                                         const char16_t *aText,
                                         gr_segment      *aSegment)
 {
     int32_t dev2appUnits = aShapedText->GetAppUnitsPerDevUnit();
     bool rtl = aShapedText->IsRightToLeft();
@@ -264,17 +264,17 @@ gfxGraphiteShaper::SetGlyphsFromSegment(
 
         // extend cluster if necessary to reach the glyph's "after" index
         if (clusters[cIndex].baseChar + clusters[cIndex].nChars < after + 1) {
             clusters[cIndex].nChars = after + 1 - clusters[cIndex].baseChar;
         }
     }
 
     bool roundX, roundY;
-    GetRoundOffsetsToPixels(aContext->GetDrawTarget(), &roundX, &roundY);
+    GetRoundOffsetsToPixels(aDrawTarget, &roundX, &roundY);
 
     gfxShapedText::CompressedGlyph *charGlyphs =
         aShapedText->GetCharacterGlyphs() + aOffset;
 
     // now put glyphs into the textrun, one cluster at a time
     for (uint32_t i = 0; i <= cIndex; ++i) {
         const Cluster& c = clusters[i];
 
--- a/gfx/thebes/gfxGraphiteShaper.h
+++ b/gfx/thebes/gfxGraphiteShaper.h
@@ -14,28 +14,28 @@ struct gr_face;
 struct gr_font;
 struct gr_segment;
 
 class gfxGraphiteShaper : public gfxFontShaper {
 public:
     explicit gfxGraphiteShaper(gfxFont *aFont);
     virtual ~gfxGraphiteShaper();
 
-    virtual bool ShapeText(gfxContext      *aContext,
+    virtual bool ShapeText(DrawTarget      *aDrawTarget,
                            const char16_t *aText,
                            uint32_t         aOffset,
                            uint32_t         aLength,
                            int32_t          aScript,
                            bool             aVertical,
                            gfxShapedText   *aShapedText);
 
     static void Shutdown();
 
 protected:
-    nsresult SetGlyphsFromSegment(gfxContext      *aContext,
+    nsresult SetGlyphsFromSegment(DrawTarget      *aDrawTarget,
                                   gfxShapedText   *aShapedText,
                                   uint32_t         aOffset,
                                   uint32_t         aLength,
                                   const char16_t *aText,
                                   gr_segment      *aSegment);
 
     static float GrGetAdvance(const void* appFontHandle, uint16_t glyphid);
 
--- a/gfx/thebes/gfxHarfBuzzShaper.cpp
+++ b/gfx/thebes/gfxHarfBuzzShaper.cpp
@@ -1457,30 +1457,30 @@ gfxHarfBuzzShaper::InitializeVertical()
             }
         }
     }
 
     return true;
 }
 
 bool
-gfxHarfBuzzShaper::ShapeText(gfxContext      *aContext,
+gfxHarfBuzzShaper::ShapeText(DrawTarget      *aDrawTarget,
                              const char16_t *aText,
                              uint32_t         aOffset,
                              uint32_t         aLength,
                              int32_t          aScript,
                              bool             aVertical,
                              gfxShapedText   *aShapedText)
 {
     // some font back-ends require this in order to get proper hinted metrics
-    if (!mFont->SetupCairoFont(aContext->GetDrawTarget())) {
+    if (!mFont->SetupCairoFont(aDrawTarget)) {
         return false;
     }
 
-    mCallbackData.mDrawTarget = aContext->GetDrawTarget();
+    mCallbackData.mDrawTarget = aDrawTarget;
     mUseVerticalPresentationForms = false;
 
     if (!Initialize()) {
         return false;
     }
 
     if (aVertical) {
         if (!InitializeVertical()) {
@@ -1560,31 +1560,31 @@ gfxHarfBuzzShaper::ShapeText(gfxContext 
     hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
 
     hb_shape(mHBFont, buffer, features.Elements(), features.Length());
 
     if (isRightToLeft) {
         hb_buffer_reverse(buffer);
     }
 
-    nsresult rv = SetGlyphsFromRun(aContext, aShapedText, aOffset, aLength,
+    nsresult rv = SetGlyphsFromRun(aDrawTarget, aShapedText, aOffset, aLength,
                                    aText, buffer, aVertical);
 
     NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "failed to store glyphs into gfxShapedWord");
     hb_buffer_destroy(buffer);
 
     return NS_SUCCEEDED(rv);
 }
 
 #define SMALL_GLYPH_RUN 128 // some testing indicates that 90%+ of text runs
                             // will fit without requiring separate allocation
                             // for charToGlyphArray
 
 nsresult
-gfxHarfBuzzShaper::SetGlyphsFromRun(gfxContext     *aContext,
+gfxHarfBuzzShaper::SetGlyphsFromRun(DrawTarget     *aDrawTarget,
                                     gfxShapedText  *aShapedText,
                                     uint32_t        aOffset,
                                     uint32_t        aLength,
                                     const char16_t *aText,
                                     hb_buffer_t    *aBuffer,
                                     bool            aVertical)
 {
     uint32_t numGlyphs;
@@ -1613,21 +1613,20 @@ gfxHarfBuzzShaper::SetGlyphsFromRun(gfxC
             charToGlyph[loc] = i;
         }
     }
 
     int32_t glyphStart = 0; // looking for a clump that starts at this glyph
     int32_t charStart = 0; // and this char index within the range of the run
 
     bool roundI, roundB;
-    DrawTarget* drawTarget = aContext->GetDrawTarget();
     if (aVertical) {
-        GetRoundOffsetsToPixels(drawTarget, &roundB, &roundI);
+        GetRoundOffsetsToPixels(aDrawTarget, &roundB, &roundI);
     } else {
-        GetRoundOffsetsToPixels(drawTarget, &roundI, &roundB);
+        GetRoundOffsetsToPixels(aDrawTarget, &roundI, &roundB);
     }
 
     int32_t appUnitsPerDevUnit = aShapedText->GetAppUnitsPerDevUnit();
     gfxShapedText::CompressedGlyph *charGlyphs =
         aShapedText->GetCharacterGlyphs() + aOffset;
 
     // factor to convert 16.16 fixed-point pixels to app units
     // (only used if not rounding)
--- a/gfx/thebes/gfxHarfBuzzShaper.h
+++ b/gfx/thebes/gfxHarfBuzzShaper.h
@@ -22,17 +22,17 @@ public:
      * FontCallbackData struct
      */
     struct FontCallbackData {
         gfxHarfBuzzShaper* mShaper;
         mozilla::gfx::DrawTarget* mDrawTarget;
     };
 
     bool Initialize();
-    virtual bool ShapeText(gfxContext      *aContext,
+    virtual bool ShapeText(DrawTarget      *aDrawTarget,
                            const char16_t *aText,
                            uint32_t         aOffset,
                            uint32_t         aLength,
                            int32_t          aScript,
                            bool             aVertical,
                            gfxShapedText   *aShapedText);
 
     // get a given font table in harfbuzz blob form
@@ -93,17 +93,17 @@ public:
         } else {
             hbScript =
                 hb_script_t(mozilla::unicode::GetScriptTagForCode(aScript));
         }
         return hbScript;
     }
 
 protected:
-    nsresult SetGlyphsFromRun(gfxContext     *aContext,
+    nsresult SetGlyphsFromRun(DrawTarget     *aDrawTarget,
                               gfxShapedText  *aShapedText,
                               uint32_t        aOffset,
                               uint32_t        aLength,
                               const char16_t *aText,
                               hb_buffer_t    *aBuffer,
                               bool            aVertical);
 
     // retrieve glyph positions, applying advance adjustments and attachments
--- a/gfx/thebes/gfxMacFont.cpp
+++ b/gfx/thebes/gfxMacFont.cpp
@@ -115,17 +115,17 @@ gfxMacFont::~gfxMacFont()
         cairo_scaled_font_destroy(mScaledFont);
     }
     if (mFontFace) {
         cairo_font_face_destroy(mFontFace);
     }
 }
 
 bool
-gfxMacFont::ShapeText(gfxContext     *aContext,
+gfxMacFont::ShapeText(DrawTarget     *aDrawTarget,
                       const char16_t *aText,
                       uint32_t        aOffset,
                       uint32_t        aLength,
                       int32_t         aScript,
                       bool            aVertical,
                       gfxShapedText  *aShapedText)
 {
     if (!mIsValid) {
@@ -135,25 +135,25 @@ gfxMacFont::ShapeText(gfxContext     *aC
 
     // Currently, we don't support vertical shaping via CoreText,
     // so we ignore RequiresAATLayout if vertical is requested.
     if (static_cast<MacOSFontEntry*>(GetFontEntry())->RequiresAATLayout() &&
         !aVertical) {
         if (!mCoreTextShaper) {
             mCoreTextShaper = new gfxCoreTextShaper(this);
         }
-        if (mCoreTextShaper->ShapeText(aContext, aText, aOffset, aLength,
+        if (mCoreTextShaper->ShapeText(aDrawTarget, aText, aOffset, aLength,
                                        aScript, aVertical, aShapedText)) {
-            PostShapingFixup(aContext->GetDrawTarget(), aText, aOffset,
+            PostShapingFixup(aDrawTarget, aText, aOffset,
                              aLength, aVertical, aShapedText);
             return true;
         }
     }
 
-    return gfxFont::ShapeText(aContext, aText, aOffset, aLength, aScript,
+    return gfxFont::ShapeText(aDrawTarget, aText, aOffset, aLength, aScript,
                               aVertical, aShapedText);
 }
 
 bool
 gfxMacFont::SetupCairoFont(DrawTarget* aDrawTarget)
 {
     if (cairo_scaled_font_status(mScaledFont) != CAIRO_STATUS_SUCCESS) {
         // Don't cairo_set_scaled_font as that would propagate the error to
@@ -163,23 +163,23 @@ gfxMacFont::SetupCairoFont(DrawTarget* a
     cairo_set_scaled_font(gfxFont::RefCairo(aDrawTarget), mScaledFont);
     return true;
 }
 
 gfxFont::RunMetrics
 gfxMacFont::Measure(gfxTextRun *aTextRun,
                     uint32_t aStart, uint32_t aEnd,
                     BoundingBoxType aBoundingBoxType,
-                    gfxContext *aRefContext,
+                    DrawTarget *aRefDrawTarget,
                     Spacing *aSpacing,
                     uint16_t aOrientation)
 {
     gfxFont::RunMetrics metrics =
         gfxFont::Measure(aTextRun, aStart, aEnd,
-                         aBoundingBoxType, aRefContext, aSpacing,
+                         aBoundingBoxType, aRefDrawTarget, aSpacing,
                          aOrientation);
 
     // if aBoundingBoxType is not TIGHT_HINTED_OUTLINE_EXTENTS then we need to add
     // a pixel column each side of the bounding box in case of antialiasing "bleed"
     if (aBoundingBoxType != TIGHT_HINTED_OUTLINE_EXTENTS &&
         metrics.mBoundingBox.width > 0) {
         metrics.mBoundingBox.x -= aTextRun->GetAppUnitsPerDevUnit();
         metrics.mBoundingBox.width += aTextRun->GetAppUnitsPerDevUnit() * 2;
--- a/gfx/thebes/gfxMacFont.h
+++ b/gfx/thebes/gfxMacFont.h
@@ -29,17 +29,17 @@ public:
     }
 
     virtual bool SetupCairoFont(DrawTarget* aDrawTarget) override;
 
     /* override Measure to add padding for antialiasing */
     virtual RunMetrics Measure(gfxTextRun *aTextRun,
                                uint32_t aStart, uint32_t aEnd,
                                BoundingBoxType aBoundingBoxType,
-                               gfxContext *aContextForTightBoundingBox,
+                               DrawTarget *aDrawTargetForTightBoundingBox,
                                Spacing *aSpacing,
                                uint16_t aOrientation) override;
 
     // We need to provide hinted (non-linear) glyph widths if using a font
     // with embedded color bitmaps (Apple Color Emoji), as Core Text renders
     // the glyphs with non-linear scaling at small pixel sizes.
     virtual bool ProvidesGlyphWidths() const override {
         return mFontEntry->HasFontTable(TRUETYPE_TAG('s','b','i','x'));
@@ -62,17 +62,17 @@ public:
     virtual FontType GetType() const override { return FONT_TYPE_MAC; }
 
 protected:
     virtual const Metrics& GetHorizontalMetrics() override {
         return mMetrics;
     }
 
     // override to prefer CoreText shaping with fonts that depend on AAT
-    virtual bool ShapeText(gfxContext     *aContext,
+    virtual bool ShapeText(DrawTarget     *aDrawTarget,
                            const char16_t *aText,
                            uint32_t        aOffset,
                            uint32_t        aLength,
                            int32_t         aScript,
                            bool            aVertical,
                            gfxShapedText  *aShapedText) override;
 
     void InitMetrics();
--- a/gfx/thebes/gfxTextRun.cpp
+++ b/gfx/thebes/gfxTextRun.cpp
@@ -570,17 +570,18 @@ gfxTextRun::Draw(gfxContext *aContext, g
     gfxFloat direction = GetDirection();
 
     if (skipDrawing) {
         // We don't need to draw anything;
         // but if the caller wants advance width, we need to compute it here
         if (aAdvanceWidth) {
             gfxTextRun::Metrics metrics = MeasureText(aStart, aLength,
                                                       gfxFont::LOOSE_INK_EXTENTS,
-                                                      aContext, aProvider);
+                                                      aContext->GetDrawTarget(),
+                                                      aProvider);
             *aAdvanceWidth = metrics.mAdvanceWidth * direction;
         }
 
         // return without drawing
         return;
     }
 
     // synthetic bolding draws glyphs twice ==> colors with opacity won't draw
@@ -591,17 +592,18 @@ gfxTextRun::Draw(gfxContext *aContext, g
 
     if (aDrawMode == DrawMode::GLYPH_FILL &&
         HasNonOpaqueNonTransparentColor(aContext, currentColor) &&
         HasSyntheticBold(this, aStart, aLength)) {
         needToRestore = true;
         // measure text, use the bounding box
         gfxTextRun::Metrics metrics = MeasureText(aStart, aLength,
                                                   gfxFont::LOOSE_INK_EXTENTS,
-                                                  aContext, aProvider);
+                                                  aContext->GetDrawTarget(),
+                                                  aProvider);
         metrics.mBoundingBox.MoveBy(aPt);
         syntheticBoldBuffer.PushSolidColor(metrics.mBoundingBox, currentColor,
                                            GetAppUnitsPerDevUnit());
     }
 
     // Set up parameters that will be constant across all glyph runs we need
     // to draw, regardless of the font used.
     TextRunDrawParams params;
@@ -708,48 +710,49 @@ gfxTextRun::DrawEmphasisMarks(gfxContext
             ComputePartialLigatureWidth(ligatureRunEnd, end, aProvider);
     }
 }
 
 void
 gfxTextRun::AccumulateMetricsForRun(gfxFont *aFont,
                                     uint32_t aStart, uint32_t aEnd,
                                     gfxFont::BoundingBoxType aBoundingBoxType,
-                                    gfxContext *aRefContext,
+                                    DrawTarget* aRefDrawTarget,
                                     PropertyProvider *aProvider,
                                     uint32_t aSpacingStart, uint32_t aSpacingEnd,
                                     uint16_t aOrientation,
                                     Metrics *aMetrics)
 {
     nsAutoTArray<PropertyProvider::Spacing,200> spacingBuffer;
     bool haveSpacing = GetAdjustedSpacingArray(aStart, aEnd, aProvider,
         aSpacingStart, aSpacingEnd, &spacingBuffer);
-    Metrics metrics = aFont->Measure(this, aStart, aEnd, aBoundingBoxType, aRefContext,
+    Metrics metrics = aFont->Measure(this, aStart, aEnd, aBoundingBoxType,
+                                     aRefDrawTarget,
                                      haveSpacing ? spacingBuffer.Elements() : nullptr,
                                      aOrientation);
     aMetrics->CombineWith(metrics, IsRightToLeft());
 }
 
 void
 gfxTextRun::AccumulatePartialLigatureMetrics(gfxFont *aFont,
     uint32_t aStart, uint32_t aEnd,
-    gfxFont::BoundingBoxType aBoundingBoxType, gfxContext *aRefContext,
+    gfxFont::BoundingBoxType aBoundingBoxType, DrawTarget* aRefDrawTarget,
     PropertyProvider *aProvider, uint16_t aOrientation, Metrics *aMetrics)
 {
     if (aStart >= aEnd)
         return;
 
     // Measure partial ligature. We hack this by clipping the metrics in the
     // same way we clip the drawing.
     LigatureData data = ComputeLigatureData(aStart, aEnd, aProvider);
 
     // First measure the complete ligature
     Metrics metrics;
     AccumulateMetricsForRun(aFont, data.mLigatureStart, data.mLigatureEnd,
-                            aBoundingBoxType, aRefContext,
+                            aBoundingBoxType, aRefDrawTarget,
                             aProvider, aStart, aEnd, aOrientation, &metrics);
 
     // Clip the bounding box to the ligature part
     gfxFloat bboxLeft = metrics.mBoundingBox.X();
     gfxFloat bboxRight = metrics.mBoundingBox.XMost();
     // Where we are going to start "drawing" relative to our left baseline origin
     gfxFloat origin = IsRightToLeft() ? metrics.mAdvanceWidth - data.mPartAdvance : 0;
     ClipPartialLigature(this, &bboxLeft, &bboxRight, origin, &data);
@@ -764,64 +767,64 @@ gfxTextRun::AccumulatePartialLigatureMet
     metrics.mAdvanceWidth = data.mPartWidth;
 
     aMetrics->CombineWith(metrics, IsRightToLeft());
 }
 
 gfxTextRun::Metrics
 gfxTextRun::MeasureText(uint32_t aStart, uint32_t aLength,
                         gfxFont::BoundingBoxType aBoundingBoxType,
-                        gfxContext *aRefContext,
+                        DrawTarget* aRefDrawTarget,
                         PropertyProvider *aProvider)
 {
     NS_ASSERTION(aStart + aLength <= GetLength(), "Substring out of range");
 
     Metrics accumulatedMetrics;
     GlyphRunIterator iter(this, aStart, aLength);
     while (iter.NextRun()) {
         gfxFont *font = iter.GetGlyphRun()->mFont;
         uint32_t start = iter.GetStringStart();
         uint32_t end = iter.GetStringEnd();
         uint32_t ligatureRunStart = start;
         uint32_t ligatureRunEnd = end;
         ShrinkToLigatureBoundaries(&ligatureRunStart, &ligatureRunEnd);
 
         AccumulatePartialLigatureMetrics(font, start, ligatureRunStart,
-            aBoundingBoxType, aRefContext, aProvider,
+            aBoundingBoxType, aRefDrawTarget, aProvider,
             iter.GetGlyphRun()->mOrientation, &accumulatedMetrics);
 
         // XXX This sucks. We have to get glyph extents just so we can detect
         // glyphs outside the font box, even when aBoundingBoxType is LOOSE,
         // even though in almost all cases we could get correct results just
         // by getting some ascent/descent from the font and using our stored
         // advance widths.
         AccumulateMetricsForRun(font,
             ligatureRunStart, ligatureRunEnd, aBoundingBoxType,
-            aRefContext, aProvider, ligatureRunStart, ligatureRunEnd,
+            aRefDrawTarget, aProvider, ligatureRunStart, ligatureRunEnd,
             iter.GetGlyphRun()->mOrientation, &accumulatedMetrics);
 
         AccumulatePartialLigatureMetrics(font, ligatureRunEnd, end,
-            aBoundingBoxType, aRefContext, aProvider,
+            aBoundingBoxType, aRefDrawTarget, aProvider,
             iter.GetGlyphRun()->mOrientation, &accumulatedMetrics);
     }
 
     return accumulatedMetrics;
 }
 
 #define MEASUREMENT_BUFFER_SIZE 100
 
 uint32_t
 gfxTextRun::BreakAndMeasureText(uint32_t aStart, uint32_t aMaxLength,
                                 bool aLineBreakBefore, gfxFloat aWidth,
                                 PropertyProvider *aProvider,
                                 SuppressBreak aSuppressBreak,
                                 gfxFloat *aTrimWhitespace,
                                 Metrics *aMetrics,
                                 gfxFont::BoundingBoxType aBoundingBoxType,
-                                gfxContext *aRefContext,
+                                DrawTarget* aRefDrawTarget,
                                 bool *aUsedHyphenation,
                                 uint32_t *aLastBreak,
                                 bool aCanWordWrap,
                                 gfxBreakPriority *aBreakPriority)
 {
     aMaxLength = std::min(aMaxLength, GetLength() - aStart);
 
     NS_ASSERTION(aStart + aMaxLength <= GetLength(), "Substring out of range");
@@ -957,23 +960,23 @@ gfxTextRun::BreakAndMeasureText(uint32_t
         trimmableChars = lastBreakTrimmableChars;
         trimmableAdvance = lastBreakTrimmableAdvance;
         usedHyphenation = lastBreakUsedHyphenation;
     } else {
         charsFit = aMaxLength;
     }
 
     if (aMetrics) {
-        *aMetrics = MeasureText(aStart, charsFit,
-            aBoundingBoxType, aRefContext, aProvider);
+        *aMetrics = MeasureText(aStart, charsFit, aBoundingBoxType,
+                                aRefDrawTarget, aProvider);
         if (trimmableChars) {
             Metrics trimMetrics =
                 MeasureText(aStart + charsFit - trimmableChars,
                             trimmableChars, aBoundingBoxType,
-                            aRefContext, aProvider);
+                            aRefDrawTarget, aProvider);
             aMetrics->mAdvanceWidth -= trimMetrics.mAdvanceWidth;
         }
     }
     if (aTrimWhitespace) {
         *aTrimWhitespace = trimmableAdvance;
     }
     if (aUsedHyphenation) {
         *aUsedHyphenation = usedHyphenation;
@@ -1027,18 +1030,17 @@ gfxTextRun::GetAdvanceWidth(uint32_t aSt
     }
 
     return result + GetAdvanceForGlyphs(ligatureRunStart, ligatureRunEnd);
 }
 
 bool
 gfxTextRun::SetLineBreaks(uint32_t aStart, uint32_t aLength,
                           bool aLineBreakBefore, bool aLineBreakAfter,
-                          gfxFloat *aAdvanceWidthDelta,
-                          gfxContext *aRefContext)
+                          gfxFloat *aAdvanceWidthDelta)
 {
     // Do nothing because our shaping does not currently take linebreaks into
     // account. There is no change in advance width.
     if (aAdvanceWidthDelta) {
         *aAdvanceWidthDelta = 0;
     }
     return false;
 }
@@ -1312,32 +1314,32 @@ gfxTextRun::ClearGlyphsAndCharacters()
 {
     ResetGlyphRuns();
     memset(reinterpret_cast<char*>(mCharacterGlyphs), 0,
            mLength * sizeof(CompressedGlyph));
     mDetailedGlyphs = nullptr;
 }
 
 void
-gfxTextRun::SetSpaceGlyph(gfxFont *aFont, gfxContext *aContext,
+gfxTextRun::SetSpaceGlyph(gfxFont* aFont, DrawTarget* aDrawTarget,
                           uint32_t aCharIndex, uint16_t aOrientation)
 {
     if (SetSpaceGlyphIfSimple(aFont, aCharIndex, ' ', aOrientation)) {
         return;
     }
 
     aFont->InitWordCache();
     static const uint8_t space = ' ';
     uint32_t flags = gfxTextRunFactory::TEXT_IS_8BIT |
                      gfxTextRunFactory::TEXT_IS_ASCII |
                      gfxTextRunFactory::TEXT_IS_PERSISTENT |
                      aOrientation;
     bool vertical =
         (GetFlags() & gfxTextRunFactory::TEXT_ORIENT_VERTICAL_UPRIGHT) != 0;
-    gfxShapedWord *sw = aFont->GetShapedWord(aContext,
+    gfxShapedWord* sw = aFont->GetShapedWord(aDrawTarget,
                                              &space, 1,
                                              gfxShapedWord::HashMix(0, ' '), 
                                              MOZ_SCRIPT_LATIN,
                                              vertical,
                                              mAppUnitsPerDevUnit,
                                              flags,
                                              nullptr);
     if (sw) {
@@ -1373,17 +1375,17 @@ gfxTextRun::SetSpaceGlyphIfSimple(gfxFon
     if (aSpaceChar == ' ') {
         g.SetIsSpace();
     }
     GetCharacterGlyphs()[aCharIndex] = g;
     return true;
 }
 
 void
-gfxTextRun::FetchGlyphExtents(gfxContext *aRefContext)
+gfxTextRun::FetchGlyphExtents(DrawTarget* aRefDrawTarget)
 {
     bool needsGlyphExtents = NeedsGlyphExtents(this);
     if (!needsGlyphExtents && !mDetailedGlyphs)
         return;
 
     uint32_t i, runCount = mGlyphRuns.Length();
     CompressedGlyph *charGlyphs = mCharacterGlyphs;
     for (i = 0; i < runCount; ++i) {
@@ -1405,52 +1407,52 @@ gfxTextRun::FetchGlyphExtents(gfxContext
             const gfxTextRun::CompressedGlyph *glyphData = &charGlyphs[j];
             if (glyphData->IsSimpleGlyph()) {
                 // If we're in speed mode, don't set up glyph extents here; we'll
                 // just return "optimistic" glyph bounds later
                 if (needsGlyphExtents) {
                     uint32_t glyphIndex = glyphData->GetSimpleGlyph();
                     if (!extents->IsGlyphKnown(glyphIndex)) {
                         if (!fontIsSetup) {
-                            if (!font->SetupCairoFont(aRefContext->GetDrawTarget())) {
+                            if (!font->SetupCairoFont(aRefDrawTarget)) {
                                 NS_WARNING("failed to set up font for glyph extents");
                                 break;
                             }
                             fontIsSetup = true;
                         }
 #ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
                         ++gGlyphExtentsSetupEagerSimple;
 #endif
-                        font->SetupGlyphExtents(aRefContext->GetDrawTarget(),
+                        font->SetupGlyphExtents(aRefDrawTarget,
                                                 glyphIndex, false, extents);
                     }
                 }
             } else if (!glyphData->IsMissing()) {
                 uint32_t glyphCount = glyphData->GetGlyphCount();
                 if (glyphCount == 0) {
                     continue;
                 }
                 const gfxTextRun::DetailedGlyph *details = GetDetailedGlyphs(j);
                 if (!details) {
                     continue;
                 }
                 for (uint32_t k = 0; k < glyphCount; ++k, ++details) {
                     uint32_t glyphIndex = details->mGlyphID;
                     if (!extents->IsGlyphKnownWithTightExtents(glyphIndex)) {
                         if (!fontIsSetup) {
-                            if (!font->SetupCairoFont(aRefContext->GetDrawTarget())) {
+                            if (!font->SetupCairoFont(aRefDrawTarget)) {
                                 NS_WARNING("failed to set up font for glyph extents");
                                 break;
                             }
                             fontIsSetup = true;
                         }
 #ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
                         ++gGlyphExtentsSetupEagerTight;
 #endif
-                        font->SetupGlyphExtents(aRefContext->GetDrawTarget(),
+                        font->SetupGlyphExtents(aRefDrawTarget,
                                                 glyphIndex, true, extents);
                     }
                 }
             }
         }
     }
 }
 
@@ -1983,26 +1985,26 @@ gfxFontGroup::MakeSpaceTextRun(const Par
         // render something for size 0 fonts.
         textRun->AddGlyphRun(font, gfxTextRange::kFontGroup, 0, false,
                              orientation);
     }
     else {
         if (font->GetSpaceGlyph()) {
             // Normally, the font has a cached space glyph, so we can avoid
             // the cost of calling FindFontForChar.
-            textRun->SetSpaceGlyph(font, aParams->mContext, 0, orientation);
+            textRun->SetSpaceGlyph(font, aParams->mDrawTarget, 0, orientation);
         } else {
             // In case the primary font doesn't have <space> (bug 970891),
             // find one that does.
             uint8_t matchType;
             RefPtr<gfxFont> spaceFont =
                 FindFontForChar(' ', 0, 0, MOZ_SCRIPT_LATIN, nullptr,
                                 &matchType);
             if (spaceFont) {
-                textRun->SetSpaceGlyph(spaceFont, aParams->mContext, 0,
+                textRun->SetSpaceGlyph(spaceFont, aParams->mDrawTarget, 0,
                                        orientation);
             }
         }
     }
 
     // Note that the gfxGlyphExtents glyph bounds storage for the font will
     // always contain an entry for the font's space glyph, so we don't have
     // to call FetchGlyphExtents here.
@@ -2024,41 +2026,42 @@ gfxFontGroup::MakeBlankTextRun(uint32_t 
         orientation = TEXT_ORIENT_VERTICAL_UPRIGHT;
     }
     textRun->AddGlyphRun(GetFirstValidFont(), gfxTextRange::kFontGroup, 0, false,
                          orientation);
     return textRun;
 }
 
 gfxTextRun *
-gfxFontGroup::MakeHyphenTextRun(gfxContext *aCtx, uint32_t aAppUnitsPerDevUnit)
+gfxFontGroup::MakeHyphenTextRun(DrawTarget* aDrawTarget,
+                                uint32_t aAppUnitsPerDevUnit)
 {
     // only use U+2010 if it is supported by the first font in the group;
     // it's better to use ASCII '-' from the primary font than to fall back to
     // U+2010 from some other, possibly poorly-matching face
     static const char16_t hyphen = 0x2010;
     gfxFont *font = GetFirstValidFont(uint32_t(hyphen));
     if (font->HasCharacter(hyphen)) {
-        return MakeTextRun(&hyphen, 1, aCtx, aAppUnitsPerDevUnit,
+        return MakeTextRun(&hyphen, 1, aDrawTarget, aAppUnitsPerDevUnit,
                            gfxFontGroup::TEXT_IS_PERSISTENT, nullptr);
     }
 
     static const uint8_t dash = '-';
-    return MakeTextRun(&dash, 1, aCtx, aAppUnitsPerDevUnit,
+    return MakeTextRun(&dash, 1, aDrawTarget, aAppUnitsPerDevUnit,
                        gfxFontGroup::TEXT_IS_PERSISTENT, nullptr);
 }
 
 gfxFloat
 gfxFontGroup::GetHyphenWidth(gfxTextRun::PropertyProvider *aProvider)
 {
     if (mHyphenWidth < 0) {
-        RefPtr<gfxContext> ctx(aProvider->GetContext());
-        if (ctx) {
+        RefPtr<DrawTarget> dt(aProvider->GetDrawTarget());
+        if (dt) {
             nsAutoPtr<gfxTextRun>
-                hyphRun(MakeHyphenTextRun(ctx,
+                hyphRun(MakeHyphenTextRun(dt,
                                           aProvider->GetAppUnitsPerDevUnit()));
             mHyphenWidth = hyphRun.get() ?
                 hyphRun->GetAdvanceWidth(0, hyphRun->GetLength(), nullptr) : 0;
         }
     }
     return mHyphenWidth;
 }
 
@@ -2085,19 +2088,19 @@ gfxFontGroup::MakeTextRun(const uint8_t 
     }
 
     gfxTextRun *textRun = gfxTextRun::Create(aParams, aLength,
                                              this, aFlags);
     if (!textRun) {
         return nullptr;
     }
 
-    InitTextRun(aParams->mContext, textRun, aString, aLength, aMFR);
-
-    textRun->FetchGlyphExtents(aParams->mContext);
+    InitTextRun(aParams->mDrawTarget, textRun, aString, aLength, aMFR);
+
+    textRun->FetchGlyphExtents(aParams->mDrawTarget);
 
     return textRun;
 }
 
 gfxTextRun *
 gfxFontGroup::MakeTextRun(const char16_t *aString, uint32_t aLength,
                           const Parameters *aParams, uint32_t aFlags,
                           gfxMissingFontRecorder *aMFR)
@@ -2114,26 +2117,26 @@ gfxFontGroup::MakeTextRun(const char16_t
     }
 
     gfxTextRun *textRun = gfxTextRun::Create(aParams, aLength,
                                              this, aFlags);
     if (!textRun) {
         return nullptr;
     }
 
-    InitTextRun(aParams->mContext, textRun, aString, aLength, aMFR);
-
-    textRun->FetchGlyphExtents(aParams->mContext);
+    InitTextRun(aParams->mDrawTarget, textRun, aString, aLength, aMFR);
+
+    textRun->FetchGlyphExtents(aParams->mDrawTarget);
 
     return textRun;
 }
 
 template<typename T>
 void
-gfxFontGroup::InitTextRun(gfxContext *aContext,
+gfxFontGroup::InitTextRun(DrawTarget* aDrawTarget,
                           gfxTextRun *aTextRun,
                           const T *aString,
                           uint32_t aLength,
                           gfxMissingFontRecorder *aMFR)
 {
     NS_ASSERTION(aLength > 0, "don't call InitTextRun for a zero-length run");
 
     // we need to do numeral processing even on 8-bit text,
@@ -2202,17 +2205,17 @@ gfxFontGroup::InitTextRun(gfxContext *aC
                                                                 "normal")),
                         mStyle.size,
                         sizeof(T),
                         str.get()));
             }
 
             // the text is still purely 8-bit; bypass the script-run itemizer
             // and treat it as a single Latin run
-            InitScriptRun(aContext, aTextRun, aString,
+            InitScriptRun(aDrawTarget, aTextRun, aString,
                           0, aLength, MOZ_SCRIPT_LATIN, aMFR);
         } else {
             const char16_t *textPtr;
             if (transformedString) {
                 textPtr = transformedString.get();
             } else {
                 // typecast to avoid compilation error for the 8-bit version,
                 // even though this is dead code in that case
@@ -2248,17 +2251,17 @@ gfxFontGroup::InitTextRun(gfxContext *aC
                             (mStyle.style & NS_FONT_STYLE_ITALIC ? "italic" :
                             (mStyle.style & NS_FONT_STYLE_OBLIQUE ? "oblique" :
                                                                     "normal")),
                             mStyle.size,
                             sizeof(T),
                             NS_ConvertUTF16toUTF8(textPtr + runStart, runLen).get()));
                 }
 
-                InitScriptRun(aContext, aTextRun, textPtr + runStart,
+                InitScriptRun(aDrawTarget, aTextRun, textPtr + runStart,
                               runStart, runLimit - runStart, runScript, aMFR);
             }
         }
 
         // if shaping was aborted due to lack of feature support, clear out
         // glyph runs and redo shaping with fallback forced on
         if (aTextRun->GetShapingState() == gfxTextRun::eShapingState_Aborted) {
             redo = true;
@@ -2295,17 +2298,17 @@ IsPUA(uint32_t aUSV)
 {
     // We could look up the General Category of the codepoint here,
     // but it's simpler to check PUA codepoint ranges.
     return (aUSV >= 0xE000 && aUSV <= 0xF8FF) || (aUSV >= 0xF0000);
 }
 
 template<typename T>
 void
-gfxFontGroup::InitScriptRun(gfxContext *aContext,
+gfxFontGroup::InitScriptRun(DrawTarget* aDrawTarget,
                             gfxTextRun *aTextRun,
                             const T *aString, // text for this script run,
                                               // not the entire textrun
                             uint32_t aOffset, // position of the script run
                                               // within the textrun
                             uint32_t aLength, // length of the script run
                             int32_t aRunScript,
                             gfxMissingFontRecorder *aMFR)
@@ -2337,17 +2340,17 @@ gfxFontGroup::InitScriptRun(gfxContext *
             range.orientation == gfxTextRunFactory::TEXT_ORIENT_VERTICAL_UPRIGHT;
         // create the glyph run for this range
         if (matchedFont && mStyle.noFallbackVariantFeatures) {
             // common case - just do glyph layout and record the
             // resulting positioned glyphs
             aTextRun->AddGlyphRun(matchedFont, range.matchType,
                                   aOffset + runStart, (matchedLength > 0),
                                   range.orientation);
-            if (!matchedFont->SplitAndInitTextRun(aContext, aTextRun,
+            if (!matchedFont->SplitAndInitTextRun(aDrawTarget, aTextRun,
                                                   aString + runStart,
                                                   aOffset + runStart,
                                                   matchedLength,
                                                   aRunScript,
                                                   vertical)) {
                 // glyph layout failed! treat as missing glyphs
                 matchedFont = nullptr;
             }
@@ -2377,34 +2380,34 @@ gfxFontGroup::InitScriptRun(gfxContext *
                     return;
                 }
 
                 RefPtr<gfxFont> subSuperFont =
                     matchedFont->GetSubSuperscriptFont(aTextRun->GetAppUnitsPerDevUnit());
                 aTextRun->AddGlyphRun(subSuperFont, range.matchType,
                                       aOffset + runStart, (matchedLength > 0),
                                       range.orientation);
-                if (!subSuperFont->SplitAndInitTextRun(aContext, aTextRun,
+                if (!subSuperFont->SplitAndInitTextRun(aDrawTarget, aTextRun,
                                                        aString + runStart,
                                                        aOffset + runStart,
                                                        matchedLength,
                                                        aRunScript,
                                                        vertical)) {
                     // glyph layout failed! treat as missing glyphs
                     matchedFont = nullptr;
                 }
             } else if (mStyle.variantCaps != NS_FONT_VARIANT_CAPS_NORMAL &&
                        !matchedFont->SupportsVariantCaps(aRunScript,
                                                          mStyle.variantCaps,
                                                          petiteToSmallCaps,
                                                          syntheticLower,
                                                          syntheticUpper))
             {
                 // fallback for small-caps variant glyphs
-                if (!matchedFont->InitFakeSmallCapsRun(aContext, aTextRun,
+                if (!matchedFont->InitFakeSmallCapsRun(aDrawTarget, aTextRun,
                                                        aString + runStart,
                                                        aOffset + runStart,
                                                        matchedLength,
                                                        range.matchType,
                                                        range.orientation,
                                                        aRunScript,
                                                        syntheticLower,
                                                        syntheticUpper)) {
@@ -2422,17 +2425,17 @@ gfxFontGroup::InitScriptRun(gfxContext *
                     aTextRun->SetShapingState(gfxTextRun::eShapingState_Aborted);
                     return;
                 }
 
                 // do glyph layout and record the resulting positioned glyphs
                 aTextRun->AddGlyphRun(matchedFont, range.matchType,
                                       aOffset + runStart, (matchedLength > 0),
                                       range.orientation);
-                if (!matchedFont->SplitAndInitTextRun(aContext, aTextRun,
+                if (!matchedFont->SplitAndInitTextRun(aDrawTarget, aTextRun,
                                                       aString + runStart,
                                                       aOffset + runStart,
                                                       matchedLength,
                                                       aRunScript,
                                                       vertical)) {
                     // glyph layout failed! treat as missing glyphs
                     matchedFont = nullptr;
                 }
@@ -2528,17 +2531,17 @@ gfxFontGroup::InitScriptRun(gfxContext *
 
     if (aMFR && missingChars) {
         aMFR->RecordScript(aRunScript);
     }
 }
 
 gfxTextRun *
 gfxFontGroup::GetEllipsisTextRun(int32_t aAppUnitsPerDevPixel, uint32_t aFlags,
-                                 LazyReferenceContextGetter& aRefContextGetter)
+                                 LazyReferenceDrawTargetGetter& aRefDrawTargetGetter)
 {
     MOZ_ASSERT(!(aFlags & ~TEXT_ORIENT_MASK),
                "flags here should only be used to specify orientation");
     if (mCachedEllipsisTextRun &&
         (mCachedEllipsisTextRun->GetFlags() & TEXT_ORIENT_MASK) == aFlags &&
         mCachedEllipsisTextRun->GetAppUnitsPerDevUnit() == aAppUnitsPerDevPixel) {
         return mCachedEllipsisTextRun;
     }
@@ -2547,19 +2550,19 @@ gfxFontGroup::GetEllipsisTextRun(int32_t
     // otherwise use three ASCII periods as fallback.
     gfxFont* firstFont = GetFirstValidFont(uint32_t(kEllipsisChar[0]));
     nsString ellipsis = firstFont->HasCharacter(kEllipsisChar[0])
         ? nsDependentString(kEllipsisChar,
                             ArrayLength(kEllipsisChar) - 1)
         : nsDependentString(kASCIIPeriodsChar,
                             ArrayLength(kASCIIPeriodsChar) - 1);
 
-    RefPtr<gfxContext> refCtx = aRefContextGetter.GetRefContext();
+    RefPtr<DrawTarget> refDT = aRefDrawTargetGetter.GetRefDrawTarget();
     Parameters params = {
-        refCtx, nullptr, nullptr, nullptr, 0, aAppUnitsPerDevPixel
+        refDT, nullptr, nullptr, nullptr, 0, aAppUnitsPerDevPixel
     };
     gfxTextRun* textRun =
         MakeTextRun(ellipsis.get(), ellipsis.Length(), &params,
                     aFlags | TEXT_IS_PERSISTENT, nullptr);
     if (!textRun) {
         return nullptr;
     }
     mCachedEllipsisTextRun = textRun;
--- a/gfx/thebes/gfxTextRun.h
+++ b/gfx/thebes/gfxTextRun.h
@@ -77,26 +77,26 @@ struct gfxTextRunDrawCallbacks {
  * there are no line breaks. The textrun can record line breaks before or after
  * any given cluster. (Line breaks specified inside clusters are ignored.)
  * 
  * It is important that zero-length substrings are handled correctly. This will
  * be on the test!
  */
 class gfxTextRun : public gfxShapedText {
 public:
-
     // Override operator delete to properly free the object that was
     // allocated via malloc.
     void operator delete(void* p) {
         free(p);
     }
 
     virtual ~gfxTextRun();
 
     typedef gfxFont::RunMetrics Metrics;
+    typedef mozilla::gfx::DrawTarget DrawTarget;
 
     // Public textrun API for general use
 
     bool IsClusterStart(uint32_t aPos) const {
         NS_ASSERTION(aPos < GetLength(), "aPos out of range");
         return mCharacterGlyphs[aPos].IsClusterStart();
     }
     bool IsLigatureGroupStart(uint32_t aPos) const {
@@ -189,17 +189,17 @@ public:
          * CLUSTER_START, then character i-1 must have zero after-spacing and
          * character i must have zero before-spacing.
          */
         virtual void GetSpacing(uint32_t aStart, uint32_t aLength,
                                 Spacing *aSpacing) = 0;
 
         // Returns a gfxContext that can be used to measure the hyphen glyph.
         // Only called if the hyphen width is requested.
-        virtual already_AddRefed<gfxContext> GetContext() = 0;
+        virtual already_AddRefed<DrawTarget> GetDrawTarget() = 0;
 
         // Return the appUnitsPerDevUnit value to be used when measuring.
         // Only called if the hyphen width is requested.
         virtual uint32_t GetAppUnitsPerDevUnit() = 0;
     };
 
     class ClusterIterator {
     public:
@@ -262,18 +262,18 @@ public:
 
     /**
      * Computes the ReflowMetrics for a substring.
      * Uses GetSpacing from aBreakProvider.
      * @param aBoundingBoxType which kind of bounding box (loose/tight)
      */
     Metrics MeasureText(uint32_t aStart, uint32_t aLength,
                         gfxFont::BoundingBoxType aBoundingBoxType,
-                        gfxContext *aRefContextForTightBoundingBox,
-                        PropertyProvider *aProvider);
+                        DrawTarget* aDrawTargetForTightBoundingBox,
+                        PropertyProvider* aProvider);
 
     /**
      * Computes just the advance width for a substring.
      * Uses GetSpacing from aBreakProvider.
      * If aSpacing is not null, the spacing attached before and after
      * the substring would be returned in it. NOTE: the spacing is
      * included in the advance width.
      */
@@ -305,18 +305,17 @@ public:
      * function is virtual so that gfxTextRun subclasses can reshape
      * properly.
      * 
      * @param aAdvanceWidthDelta if non-null, returns the change in advance
      * width of the given range.
      */
     virtual bool SetLineBreaks(uint32_t aStart, uint32_t aLength,
                                  bool aLineBreakBefore, bool aLineBreakAfter,
-                                 gfxFloat *aAdvanceWidthDelta,
-                                 gfxContext *aRefContext);
+                                 gfxFloat* aAdvanceWidthDelta);
 
     enum SuppressBreak {
       eNoSuppressBreak,
       // Measure the range of text as if there is no break before it.
       eSuppressInitialBreak,
       // Measure the range of text as if it contains no break
       eSuppressAllBreaks
     };
@@ -350,17 +349,17 @@ public:
      * spaces to be trimmed; the width of the space(s) will not be included in
      * the measured string width for comparison with the limit aWidth, and
      * trimmed spaces will not be included in returned metrics. The width
      * of the trimmed spaces will be returned in aTrimWhitespace.
      * Trimmed spaces are still counted in the "characters fit" result.
      * @param aMetrics if non-null, we fill this in for the returned substring.
      * If a hyphenation break was used, the hyphen is NOT included in the returned metrics.
      * @param aBoundingBoxType whether to make the bounding box in aMetrics tight
-     * @param aRefContextForTightBoundingBox a reference context to get the
+     * @param aDrawTargetForTightBoundingbox a reference DrawTarget to get the
      * tight bounding box, if requested
      * @param aUsedHyphenation if non-null, records if we selected a hyphenation break
      * @param aLastBreak if non-null and result is aMaxLength, we set this to
      * the maximal N such that
      *       N < aMaxLength && line break at N && GetAdvanceWidth(aStart, N) <= aWidth
      *   OR  N < aMaxLength && hyphen break at N && GetAdvanceWidth(aStart, N) + GetHyphenWidth() <= aWidth
      * or UINT32_MAX if no such N exists, where GetAdvanceWidth assumes
      * the effect of
@@ -378,17 +377,17 @@ public:
      */
     uint32_t BreakAndMeasureText(uint32_t aStart, uint32_t aMaxLength,
                                  bool aLineBreakBefore, gfxFloat aWidth,
                                  PropertyProvider *aProvider,
                                  SuppressBreak aSuppressBreak,
                                  gfxFloat *aTrimWhitespace,
                                  Metrics *aMetrics,
                                  gfxFont::BoundingBoxType aBoundingBoxType,
-                                 gfxContext *aRefContextForTightBoundingBox,
+                                 DrawTarget* aDrawTargetForTightBoundingBox,
                                  bool *aUsedHyphenation,
                                  uint32_t *aLastBreak,
                                  bool aCanWordWrap,
                                  gfxBreakPriority *aBreakPriority);
 
     // Utility getters
 
     void *GetUserData() const { return mUserData; }
@@ -485,18 +484,18 @@ public:
     CompressedGlyph* GetCharacterGlyphs() final {
         NS_ASSERTION(mCharacterGlyphs, "failed to initialize mCharacterGlyphs");
         return mCharacterGlyphs;
     }
 
     // clean out results from shaping in progress, used for fallback scenarios
     void ClearGlyphsAndCharacters();
 
-    void SetSpaceGlyph(gfxFont *aFont, gfxContext *aContext, uint32_t aCharIndex,
-                       uint16_t aOrientation);
+    void SetSpaceGlyph(gfxFont* aFont, DrawTarget* aDrawTarget,
+                       uint32_t aCharIndex, uint16_t aOrientation);
 
     // Set the glyph data for the given character index to the font's
     // space glyph, IF this can be done as a "simple" glyph record
     // (not requiring a DetailedGlyph entry). This avoids the need to call
     // the font shaper and go through the shaped-word cache for most spaces.
     //
     // The parameter aSpaceChar is the original character code for which
     // this space glyph is being used; if this is U+0020, we need to record
@@ -526,17 +525,17 @@ public:
     }
 
     /**
      * Prefetch all the glyph extents needed to ensure that Measure calls
      * on this textrun not requesting tight boundingBoxes will succeed. Note
      * that some glyph extents might not be fetched due to OOM or other
      * errors.
      */
-    void FetchGlyphExtents(gfxContext *aRefContext);
+    void FetchGlyphExtents(DrawTarget* aRefDrawTarget);
 
     uint32_t CountMissingGlyphs();
     const GlyphRun *GetGlyphRuns(uint32_t *aNumGlyphRuns) {
         *aNumGlyphRuns = mGlyphRuns.Length();
         return mGlyphRuns.Elements();
     }
     // Returns the index of the GlyphRun containing the given offset.
     // Returns mGlyphRuns.Length() when aOffset is mCharacterCount.
@@ -691,25 +690,25 @@ private:
     // Advance aStart to the start of the nearest ligature; back up aEnd
     // to the nearest ligature end; may result in *aStart == *aEnd
     void ShrinkToLigatureBoundaries(uint32_t *aStart, uint32_t *aEnd);
     // result in appunits
     gfxFloat GetPartialLigatureWidth(uint32_t aStart, uint32_t aEnd, PropertyProvider *aProvider);
     void AccumulatePartialLigatureMetrics(gfxFont *aFont,
                                           uint32_t aStart, uint32_t aEnd,
                                           gfxFont::BoundingBoxType aBoundingBoxType,
-                                          gfxContext *aRefContext,
+                                          DrawTarget* aRefDrawTarget,
                                           PropertyProvider *aProvider,
                                           uint16_t aOrientation,
                                           Metrics *aMetrics);
 
     // **** measurement helper ****
     void AccumulateMetricsForRun(gfxFont *aFont, uint32_t aStart, uint32_t aEnd,
                                  gfxFont::BoundingBoxType aBoundingBoxType,
-                                 gfxContext *aRefContext,
+                                 DrawTarget* aRefDrawTarget,
                                  PropertyProvider *aProvider,
                                  uint32_t aSpacingStart, uint32_t aSpacingEnd,
                                  uint16_t aOrientation,
                                  Metrics *aMetrics);
 
     // **** drawing helper ****
     void DrawGlyphs(gfxFont *aFont, uint32_t aStart, uint32_t aEnd,
                     gfxPoint *aPt, PropertyProvider *aProvider,
@@ -788,24 +787,24 @@ public:
                                     const Parameters *aParams, uint32_t aFlags,
                                     gfxMissingFontRecorder *aMFR);
 
     /**
      * Textrun creation helper for clients that don't want to pass
      * a full Parameters record.
      */
     template<typename T>
-    gfxTextRun *MakeTextRun(const T *aString, uint32_t aLength,
-                            gfxContext *aRefContext,
+    gfxTextRun* MakeTextRun(const T* aString, uint32_t aLength,
+                            DrawTarget* aRefDrawTarget,
                             int32_t aAppUnitsPerDevUnit,
                             uint32_t aFlags,
                             gfxMissingFontRecorder *aMFR)
     {
         gfxTextRunFactory::Parameters params = {
-            aRefContext, nullptr, nullptr, nullptr, 0, aAppUnitsPerDevUnit
+            aRefDrawTarget, nullptr, nullptr, nullptr, 0, aAppUnitsPerDevUnit
         };
         return MakeTextRun(aString, aLength, &params, aFlags, aMFR);
     }
 
     /**
      * Get the (possibly-cached) width of the hyphen character.
      * The aCtx and aAppUnitsPerDevUnit parameters will be used only if
      * needed to initialize the cached hyphen width; otherwise they are
@@ -815,17 +814,17 @@ public:
 
     /**
      * Make a text run representing a single hyphen character.
      * This will use U+2010 HYPHEN if available in the first font,
      * otherwise fall back to U+002D HYPHEN-MINUS.
      * The caller is responsible for deleting the returned text run
      * when no longer required.
      */
-    gfxTextRun *MakeHyphenTextRun(gfxContext *aCtx,
+    gfxTextRun* MakeHyphenTextRun(DrawTarget* aDrawTarget,
                                   uint32_t aAppUnitsPerDevUnit);
 
     /**
      * Check whether a given font (specified by its gfxFontEntry)
      * is already in the fontgroup's list of actual fonts
      */
     bool HasFont(const gfxFontEntry *aFontEntry);
 
@@ -866,27 +865,27 @@ public:
 
     // search for a specific userfont in the list of fonts
     bool ContainsUserFont(const gfxUserFontEntry* aUserFont);
 
     bool ShouldSkipDrawing() const {
         return mSkipDrawing;
     }
 
-    class LazyReferenceContextGetter {
+    class LazyReferenceDrawTargetGetter {
     public:
-      virtual already_AddRefed<gfxContext> GetRefContext() = 0;
+      virtual already_AddRefed<DrawTarget> GetRefDrawTarget() = 0;
     };
     // The gfxFontGroup keeps ownership of this textrun.
     // It is only guaranteed to exist until the next call to GetEllipsisTextRun
     // (which might use a different appUnitsPerDev value or flags) for the font
     // group, or until UpdateUserFonts is called, or the fontgroup is destroyed.
     // Get it/use it/forget it :) - don't keep a reference that might go stale.
     gfxTextRun* GetEllipsisTextRun(int32_t aAppUnitsPerDevPixel, uint32_t aFlags,
-                                   LazyReferenceContextGetter& aRefContextGetter);
+                                   LazyReferenceDrawTargetGetter& aRefDrawTargetGetter);
 
 protected:
     // search through pref fonts for a character, return nullptr if no matching pref font
     already_AddRefed<gfxFont> WhichPrefFontSupportsChar(uint32_t aCh);
 
     already_AddRefed<gfxFont>
         WhichSystemFontSupportsChar(uint32_t aCh, uint32_t aNextCh,
                                     int32_t aRunScript);
@@ -1097,26 +1096,26 @@ protected:
     // Init this font group's font metrics. If there no bad fonts, you don't need to call this.
     // But if there are one or more bad fonts which have bad underline offset,
     // you should call this with the *first* bad font.
     void InitMetricsForBadFont(gfxFont* aBadFont);
 
     // Set up the textrun glyphs for an entire text run:
     // find script runs, and then call InitScriptRun for each
     template<typename T>
-    void InitTextRun(gfxContext *aContext,
+    void InitTextRun(DrawTarget* aDrawTarget,
                      gfxTextRun *aTextRun,
                      const T *aString,
                      uint32_t aLength,
                      gfxMissingFontRecorder *aMFR);
 
     // InitTextRun helper to handle a single script run, by finding font ranges
     // and calling each font's InitTextRun() as appropriate
     template<typename T>
-    void InitScriptRun(gfxContext *aContext,
+    void InitScriptRun(DrawTarget* aDrawTarget,
                        gfxTextRun *aTextRun,
                        const T *aString,
                        uint32_t aScriptRunStart,
                        uint32_t aScriptRunEnd,
                        int32_t aRunScript,
                        gfxMissingFontRecorder *aMFR);
 
     // Helper for font-matching:
--- a/layout/base/nsBidiPresUtils.cpp
+++ b/layout/base/nsBidiPresUtils.cpp
@@ -2207,22 +2207,24 @@ nsresult nsBidiPresUtils::ProcessText(co
   }
   return NS_OK;
 }
 
 class MOZ_STACK_CLASS nsIRenderingContextBidiProcessor final
   : public nsBidiPresUtils::BidiProcessor
 {
 public:
+  typedef mozilla::gfx::DrawTarget DrawTarget;
+
   nsIRenderingContextBidiProcessor(nsRenderingContext* aCtx,
-                                   nsRenderingContext* aTextRunConstructionContext,
+                                   DrawTarget* aTextRunConstructionDrawTarget,
                                    nsFontMetrics* aFontMetrics,
                                    const nsPoint&       aPt)
     : mCtx(aCtx)
-    , mTextRunConstructionContext(aTextRunConstructionContext)
+    , mTextRunConstructionDrawTarget(aTextRunConstructionDrawTarget)
     , mFontMetrics(aFontMetrics)
     , mPt(aPt)
   {}
 
   ~nsIRenderingContextBidiProcessor()
   {
     mFontMetrics->SetTextRunRTL(false);
   }
@@ -2234,57 +2236,57 @@ public:
     mFontMetrics->SetTextRunRTL(aDirection==NSBIDI_RTL);
     mText = aText;
     mLength = aLength;
   }
 
   virtual nscoord GetWidth() override
   {
     return nsLayoutUtils::AppUnitWidthOfString(mText, mLength, *mFontMetrics,
-                                               *mTextRunConstructionContext);
+                                               mTextRunConstructionDrawTarget);
   }
 
   virtual void DrawText(nscoord aIOffset,
                         nscoord) override
   {
     nsPoint pt(mPt);
     if (mFontMetrics->GetVertical()) {
       pt.y += aIOffset;
     } else {
       pt.x += aIOffset;
     }
     mFontMetrics->DrawString(mText, mLength, pt.x, pt.y,
-                             mCtx, mTextRunConstructionContext);
+                             mCtx, mTextRunConstructionDrawTarget);
   }
 
 private:
   nsRenderingContext* mCtx;
-  nsRenderingContext* mTextRunConstructionContext;
+  DrawTarget* mTextRunConstructionDrawTarget;
   nsFontMetrics* mFontMetrics;
   nsPoint mPt;
   const char16_t* mText;
   int32_t mLength;
 };
 
 nsresult nsBidiPresUtils::ProcessTextForRenderingContext(const char16_t*       aText,
                                                          int32_t                aLength,
                                                          nsBidiLevel            aBaseLevel,
                                                          nsPresContext*         aPresContext,
                                                          nsRenderingContext&   aRenderingContext,
-                                                         nsRenderingContext&   aTextRunConstructionContext,
+                                                         DrawTarget*           aTextRunConstructionDrawTarget,
                                                          nsFontMetrics&         aFontMetrics,
                                                          Mode                   aMode,
                                                          nscoord                aX,
                                                          nscoord                aY,
                                                          nsBidiPositionResolve* aPosResolve,
                                                          int32_t                aPosResolveCount,
                                                          nscoord*               aWidth)
 {
   nsIRenderingContextBidiProcessor processor(&aRenderingContext,
-                                             &aTextRunConstructionContext,
+                                             aTextRunConstructionDrawTarget,
                                              &aFontMetrics,
                                              nsPoint(aX, aY));
   nsBidi bidiEngine;
   return ProcessText(aText, aLength, aBaseLevel, aPresContext, processor,
                      aMode, aPosResolve, aPosResolveCount, aWidth, &bidiEngine);
 }
 
 /* static */
--- a/layout/base/nsBidiPresUtils.h
+++ b/layout/base/nsBidiPresUtils.h
@@ -6,16 +6,17 @@
 
 #ifndef nsBidiPresUtils_h___
 #define nsBidiPresUtils_h___
 
 #include "nsBidi.h"
 #include "nsBidiUtils.h"
 #include "nsHashKeys.h"
 #include "nsCoord.h"
+#include "nsRenderingContext.h"
 
 #ifdef DrawText
 #undef DrawText
 #endif
 
 struct BidiParagraphData;
 struct BidiLineData;
 class nsFontMetrics;
@@ -88,16 +89,18 @@ struct nsBidiPositionResolve
   int32_t visualLeftTwips;
   // [out] Visual width of the character, in twips.
   // If the logical position was not found, set to kNotFound.
   int32_t visualWidth;
 };
 
 class nsBidiPresUtils {
 public:
+  typedef mozilla::gfx::DrawTarget DrawTarget;
+
   nsBidiPresUtils();
   ~nsBidiPresUtils();
   
   /**
    * Interface for the processor used by ProcessText. Used by process text to
    * collect information about the width of subruns and to notify where each
    * subrun should be rendered.
    */
@@ -207,39 +210,40 @@ public:
    * @param[in,out] aPosResolve array of logical positions to resolve into visual positions; can be nullptr if this functionality is not required
    * @param aPosResolveCount number of items in the aPosResolve array
    */
   static nsresult RenderText(const char16_t*       aText,
                              int32_t                aLength,
                              nsBidiLevel            aBaseLevel,
                              nsPresContext*         aPresContext,
                              nsRenderingContext&    aRenderingContext,
-                             nsRenderingContext&    aTextRunConstructionContext,
+                             DrawTarget*            aTextRunConstructionDrawTarget,
                              nsFontMetrics&         aFontMetrics,
                              nscoord                aX,
                              nscoord                aY,
                              nsBidiPositionResolve* aPosResolve = nullptr,
                              int32_t                aPosResolveCount = 0)
   {
     return ProcessTextForRenderingContext(aText, aLength, aBaseLevel, aPresContext, aRenderingContext,
-                                          aTextRunConstructionContext,
+                                          aTextRunConstructionDrawTarget,
                                           aFontMetrics,
                                           MODE_DRAW, aX, aY, aPosResolve, aPosResolveCount, nullptr);
   }
   
   static nscoord MeasureTextWidth(const char16_t*     aText,
                                   int32_t              aLength,
                                   nsBidiLevel          aBaseLevel,
                                   nsPresContext*       aPresContext,
                                   nsRenderingContext&  aRenderingContext,
                                   nsFontMetrics&       aFontMetrics)
   {
     nscoord length;
     nsresult rv = ProcessTextForRenderingContext(aText, aLength, aBaseLevel, aPresContext,
-                                                 aRenderingContext, aRenderingContext,
+                                                 aRenderingContext,
+                                                 aRenderingContext.GetDrawTarget(),
                                                  aFontMetrics,
                                                  MODE_MEASURE, 0, 0, nullptr, 0, &length);
     return NS_SUCCEEDED(rv) ? length : 0;
   }
 
   /**
    * Check if a line is reordered, i.e., if the child frames are not
    * all laid out left-to-right.
@@ -372,17 +376,17 @@ public:
 
 private:
   static nsresult
   ProcessTextForRenderingContext(const char16_t*       aText,
                                  int32_t                aLength,
                                  nsBidiLevel            aBaseLevel,
                                  nsPresContext*         aPresContext,
                                  nsRenderingContext&    aRenderingContext,
-                                 nsRenderingContext&    aTextRunConstructionContext,
+                                 DrawTarget*            aTextRunConstructionDrawTarget,
                                  nsFontMetrics&         aFontMetrics,
                                  Mode                   aMode,
                                  nscoord                aX, // DRAW only
                                  nscoord                aY, // DRAW only
                                  nsBidiPositionResolve* aPosResolve,  /* may be null */
                                  int32_t                aPosResolveCount,
                                  nscoord*               aWidth /* may be null */);
 
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -3460,61 +3460,60 @@ nsLayoutUtils::PaintFrame(nsRenderingCon
  * @param "aBaseWidth" contains the width in twips of the portion
  * of the text that has already been measured, and aBaseInx contains
  * the index of the text that has already been measured.
  *
  * @param aTextWidth returns the (in twips) the length of the text that falls
  * before the cursor aIndex contains the index of the text where the cursor falls
  */
 bool
-nsLayoutUtils::BinarySearchForPosition(nsRenderingContext* aRendContext,
+nsLayoutUtils::BinarySearchForPosition(DrawTarget* aDrawTarget,
                                        nsFontMetrics& aFontMetrics,
                         const char16_t* aText,
                         int32_t    aBaseWidth,
                         int32_t    aBaseInx,
                         int32_t    aStartInx,
                         int32_t    aEndInx,
                         int32_t    aCursorPos,
                         int32_t&   aIndex,
                         int32_t&   aTextWidth)
 {
   int32_t range = aEndInx - aStartInx;
   if ((range == 1) || (range == 2 && NS_IS_HIGH_SURROGATE(aText[aStartInx]))) {
     aIndex   = aStartInx + aBaseInx;
     aTextWidth = nsLayoutUtils::AppUnitWidthOfString(aText, aIndex,
-                                                     aFontMetrics,
-                                                     *aRendContext);
+                                                     aFontMetrics, aDrawTarget);
     return true;
   }
 
   int32_t inx = aStartInx + (range / 2);
 
   // Make sure we don't leave a dangling low surrogate
   if (NS_IS_HIGH_SURROGATE(aText[inx-1]))
     inx++;
 
   int32_t textWidth = nsLayoutUtils::AppUnitWidthOfString(aText, inx,
                                                           aFontMetrics,
-                                                          *aRendContext);
+                                                          aDrawTarget);
 
   int32_t fullWidth = aBaseWidth + textWidth;
   if (fullWidth == aCursorPos) {
     aTextWidth = textWidth;
     aIndex = inx;
     return true;
   } else if (aCursorPos < fullWidth) {
     aTextWidth = aBaseWidth;
-    if (BinarySearchForPosition(aRendContext, aFontMetrics, aText, aBaseWidth,
+    if (BinarySearchForPosition(aDrawTarget, aFontMetrics, aText, aBaseWidth,
                                 aBaseInx, aStartInx, inx, aCursorPos, aIndex,
                                 aTextWidth)) {
       return true;
     }
   } else {
     aTextWidth = fullWidth;
-    if (BinarySearchForPosition(aRendContext, aFontMetrics, aText, aBaseWidth,
+    if (BinarySearchForPosition(aDrawTarget, aFontMetrics, aText, aBaseWidth,
                                 aBaseInx, inx, aEndInx, aCursorPos, aIndex,
                                 aTextWidth)) {
       return true;
     }
   }
   return false;
 }
 
@@ -5502,23 +5501,23 @@ static int32_t GetMaxChunkLength(nsFontM
 {
   return std::min(aFontMetrics.GetMaxStringLength(), MAX_GFX_TEXT_BUF_SIZE);
 }
 
 nscoord
 nsLayoutUtils::AppUnitWidthOfString(const char16_t *aString,
                                     uint32_t aLength,
                                     nsFontMetrics& aFontMetrics,
-                                    nsRenderingContext& aContext)
+                                    DrawTarget* aDrawTarget)
 {
   uint32_t maxChunkLength = GetMaxChunkLength(aFontMetrics);
   nscoord width = 0;
   while (aLength > 0) {
     int32_t len = FindSafeLength(aString, aLength, maxChunkLength);
-    width += aFontMetrics.GetWidth(aString, len, &aContext);
+    width += aFontMetrics.GetWidth(aString, len, aDrawTarget);
     aLength -= len;
     aString += len;
   }
   return width;
 }
 
 nscoord
 nsLayoutUtils::AppUnitWidthOfStringBidi(const char16_t* aString,
@@ -5534,61 +5533,61 @@ nsLayoutUtils::AppUnitWidthOfStringBidi(
     return nsBidiPresUtils::MeasureTextWidth(aString, aLength, level,
                                              presContext, aContext,
                                              aFontMetrics);
   }
   aFontMetrics.SetTextRunRTL(false);
   aFontMetrics.SetVertical(aFrame->GetWritingMode().IsVertical());
   aFontMetrics.SetTextOrientation(aFrame->StyleVisibility()->mTextOrientation);
   return nsLayoutUtils::AppUnitWidthOfString(aString, aLength, aFontMetrics,
-                                             aContext);
+                                             aContext.GetDrawTarget());
 }
 
 bool
 nsLayoutUtils::StringWidthIsGreaterThan(const nsString& aString,
                                         nsFontMetrics& aFontMetrics,
-                                        nsRenderingContext& aContext,
+                                        DrawTarget* aDrawTarget,
                                         nscoord aWidth)
 {
   const char16_t *string = aString.get();
   uint32_t length = aString.Length();
   uint32_t maxChunkLength = GetMaxChunkLength(aFontMetrics);
   nscoord width = 0;
   while (length > 0) {
     int32_t len = FindSafeLength(string, length, maxChunkLength);
-    width += aFontMetrics.GetWidth(string, len, &aContext);
+    width += aFontMetrics.GetWidth(string, len, aDrawTarget);
     if (width > aWidth) {
       return true;
     }
     length -= len;
     string += len;
   }
   return false;
 }
 
 nsBoundingMetrics
 nsLayoutUtils::AppUnitBoundsOfString(const char16_t* aString,
                                      uint32_t aLength,
                                      nsFontMetrics& aFontMetrics,
-                                     nsRenderingContext& aContext)
+                                     DrawTarget* aDrawTarget)
 {
   uint32_t maxChunkLength = GetMaxChunkLength(aFontMetrics);
   int32_t len = FindSafeLength(aString, aLength, maxChunkLength);
   // Assign directly in the first iteration. This ensures that
   // negative ascent/descent can be returned and the left bearing
   // is properly initialized.
   nsBoundingMetrics totalMetrics =
-    aFontMetrics.GetBoundingMetrics(aString, len, &aContext);
+    aFontMetrics.GetBoundingMetrics(aString, len, aDrawTarget);
   aLength -= len;
   aString += len;
 
   while (aLength > 0) {
     len = FindSafeLength(aString, aLength, maxChunkLength);
     nsBoundingMetrics metrics =
-      aFontMetrics.GetBoundingMetrics(aString, len, &aContext);
+      aFontMetrics.GetBoundingMetrics(aString, len, aDrawTarget);
     totalMetrics += metrics;
     aLength -= len;
     aString += len;
   }
   return totalMetrics;
 }
 
 void
@@ -5610,18 +5609,18 @@ nsLayoutUtils::DrawString(const nsIFrame
   aFontMetrics.SetTextOrientation(
     aStyleContext->StyleVisibility()->mTextOrientation);
 
   nsPresContext* presContext = aFrame->PresContext();
   if (presContext->BidiEnabled()) {
     nsBidiLevel level =
       nsBidiPresUtils::BidiLevelFromStyle(aStyleContext);
     rv = nsBidiPresUtils::RenderText(aString, aLength, level,
-                                     presContext, *aContext, *aContext,
-                                     aFontMetrics,
+                                     presContext, *aContext,
+                                     aContext->GetDrawTarget(), aFontMetrics,
                                      aPoint.x, aPoint.y);
   }
   if (NS_FAILED(rv))
   {
     aFontMetrics.SetTextRunRTL(false);
     DrawUniDirString(aString, aLength, aPoint, aFontMetrics, *aContext);
   }
 }
@@ -5633,35 +5632,37 @@ nsLayoutUtils::DrawUniDirString(const ch
                                 nsFontMetrics& aFontMetrics,
                                 nsRenderingContext& aContext)
 {
   nscoord x = aPoint.x;
   nscoord y = aPoint.y;
 
   uint32_t maxChunkLength = GetMaxChunkLength(aFontMetrics);
   if (aLength <= maxChunkLength) {
-    aFontMetrics.DrawString(aString, aLength, x, y, &aContext, &aContext);
+    aFontMetrics.DrawString(aString, aLength, x, y, &aContext,
+                            aContext.GetDrawTarget());
     return;
   }
 
   bool isRTL = aFontMetrics.GetTextRunRTL();
 
   // If we're drawing right to left, we must start at the end.
   if (isRTL) {
     x += nsLayoutUtils::AppUnitWidthOfString(aString, aLength, aFontMetrics,
-                                             aContext);
+                                             aContext.GetDrawTarget());
   }
 
   while (aLength > 0) {
     int32_t len = FindSafeLength(aString, aLength, maxChunkLength);
-    nscoord width = aFontMetrics.GetWidth(aString, len, &aContext);
+    nscoord width = aFontMetrics.GetWidth(aString, len, aContext.GetDrawTarget());
     if (isRTL) {
       x -= width;
     }
-    aFontMetrics.DrawString(aString, len, x, y, &aContext, &aContext);
+    aFontMetrics.DrawString(aString, len, x, y, &aContext,
+                            aContext.GetDrawTarget());
     if (!isRTL) {
       x += width;
     }
     aLength -= len;
     aString += len;
   }
 }
 
--- a/layout/base/nsLayoutUtils.h
+++ b/layout/base/nsLayoutUtils.h
@@ -1045,17 +1045,17 @@ public:
    * of the text that has already been measured, and aBaseInx contains
    * the index of the text that has already been measured.
    *
    * @param aTextWidth returns (in twips) the length of the text that falls
    * before the cursor aIndex contains the index of the text where the cursor
    * falls.
    */
   static bool
-  BinarySearchForPosition(nsRenderingContext* acx,
+  BinarySearchForPosition(DrawTarget* aDrawTarget,
                           nsFontMetrics& aFontMetrics,
                           const char16_t* aText,
                           int32_t    aBaseWidth,
                           int32_t    aBaseInx,
                           int32_t    aStartInx,
                           int32_t    aEndInx,
                           int32_t    aCursorPos,
                           int32_t&   aIndex,
@@ -1557,52 +1557,52 @@ public:
                                       nscoord aY, nscoord aAscent);
   // Ditto for an x position (for vertical text). Note that for vertical-rl
   // writing mode, the ascent value should be negated by the caller.
   static gfxFloat GetSnappedBaselineX(nsIFrame* aFrame, gfxContext* aContext,
                                       nscoord aX, nscoord aAscent);
 
   static nscoord AppUnitWidthOfString(char16_t aC,
                                       nsFontMetrics& aFontMetrics,
-                                      nsRenderingContext& aContext) {
-    return AppUnitWidthOfString(&aC, 1, aFontMetrics, aContext);
+                                      DrawTarget* aDrawTarget) {
+    return AppUnitWidthOfString(&aC, 1, aFontMetrics, aDrawTarget);
   }
   static nscoord AppUnitWidthOfString(const nsString& aString,
                                       nsFontMetrics& aFontMetrics,
-                                      nsRenderingContext& aContext) {
+                                      DrawTarget* aDrawTarget) {
     return nsLayoutUtils::AppUnitWidthOfString(aString.get(), aString.Length(),
-                                               aFontMetrics, aContext);
+                                               aFontMetrics, aDrawTarget);
   }
   static nscoord AppUnitWidthOfString(const char16_t *aString,
                                       uint32_t aLength,
                                       nsFontMetrics& aFontMetrics,
-                                      nsRenderingContext& aContext);
+                                      DrawTarget* aDrawTarget);
   static nscoord AppUnitWidthOfStringBidi(const nsString& aString,
                                           const nsIFrame* aFrame,
                                           nsFontMetrics& aFontMetrics,
                                           nsRenderingContext& aContext) {
     return nsLayoutUtils::AppUnitWidthOfStringBidi(aString.get(),
                                                    aString.Length(), aFrame,
                                                    aFontMetrics, aContext);
   }
   static nscoord AppUnitWidthOfStringBidi(const char16_t* aString,
                                           uint32_t aLength,
                                           const nsIFrame* aFrame,
                                           nsFontMetrics& aFontMetrics,
                                           nsRenderingContext& aContext);
 
   static bool StringWidthIsGreaterThan(const nsString& aString,
                                        nsFontMetrics& aFontMetrics,
-                                       nsRenderingContext& aContext,
+                                       DrawTarget* aDrawTarget,
                                        nscoord aWidth);
 
   static nsBoundingMetrics AppUnitBoundsOfString(const char16_t* aString,
                                                  uint32_t aLength,
                                                  nsFontMetrics& aFontMetrics,
-                                                 nsRenderingContext& aContext);
+                                                 DrawTarget* aDrawTarget);
 
   static void DrawString(const nsIFrame*       aFrame,
                          nsFontMetrics&        aFontMetrics,
                          nsRenderingContext*   aContext,
                          const char16_t*      aString,
                          int32_t               aLength,
                          nsPoint               aPoint,
                          nsStyleContext*       aStyleContext = nullptr);
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -10046,17 +10046,17 @@ void ReflowCountMgr::PaintCount(const ch
         nsGkAtoms::x_western, false, gfxFont::eHorizontal, nullptr,
         aPresContext->GetTextPerfMetrics(), *getter_AddRefs(fm));
 
       char buf[16];
       int len = snprintf_literal(buf, "%d", counter->mCount);
       nscoord x = 0, y = fm->MaxAscent();
       nscoord width, height = fm->MaxHeight();
       fm->SetTextRunRTL(false);
-      width = fm->GetWidth(buf, len, aRenderingContext);;
+      width = fm->GetWidth(buf, len, drawTarget);
 
       Color color;
       Color color2;
       if (aColor != 0) {
         color  = Color::FromABGR(aColor);
         color2 = Color(0.f, 0.f, 0.f);
       } else {
         gfx::Float rc = 0.f, gc = 0.f, bc = 0.f;
--- a/layout/doc/obsolete/line-layout.html
+++ b/layout/doc/obsolete/line-layout.html
@@ -86,17 +86,17 @@ point is. nsLineLayout supports this by 
 as well as both storing and interrogating "word" state.
 <h3>
 <u>White-space</u></h3>
 To support the white-space property, the line layout logic keeps track
 of the presence of white-space in the line as it told to reflow each inline
 frame. This allows for the compression of leading whitespace and the compression
 of adjacent whitespace that is in separate inline elements.
 <p>As a post-processing step, the TrimTrailingWhiteSpace logic is used
-to remove those pesky pices of white-space that end up being placed at
+to remove those pesky pieces of white-space that end up being placed at
 the end of a line, that shouldn't really be seen.
 <p>To support pre-formatted text that contains tab characters, the line
 layout class keeps track of the current column on behalf of the text frame
 code.
 <h3>
 <u>Vertical Alignment</u></h3>
 Vertical alignment is peformed as a two and a half pass process. The first
 pass is done during nsInlineFrame reflow: the child frames of the nsInlineFrame
--- a/layout/generic/MathMLTextRunFactory.cpp
+++ b/layout/generic/MathMLTextRunFactory.cpp
@@ -524,17 +524,17 @@ MathVariant(uint32_t aCh, uint8_t aMathV
 
 }
 
 #define TT_SSTY TRUETYPE_TAG('s', 's', 't', 'y')
 #define TT_DTLS TRUETYPE_TAG('d', 't', 'l', 's')
 
 void
 MathMLTextRunFactory::RebuildTextRun(nsTransformedTextRun* aTextRun,
-                                     gfxContext* aRefContext,
+                                     mozilla::gfx::DrawTarget* aRefDrawTarget,
                                      gfxMissingFontRecorder* aMFR)
 {
   gfxFontGroup* fontGroup = aTextRun->GetFontGroup();
 
   nsAutoString convertedString;
   nsAutoTArray<bool,50> charsToMergeArray;
   nsAutoTArray<bool,50> deletedCharsArray;
   nsAutoTArray<RefPtr<nsTransformedCharStyle>,50> styleArray;
@@ -707,17 +707,17 @@ MathMLTextRunFactory::RebuildTextRun(nsT
       charsToMergeArray.AppendElement(true);
       styleArray.AppendElement(styles[i]);
       canBreakBeforeArray.AppendElement(false);
     }
   }
 
   uint32_t flags;
   gfxTextRunFactory::Parameters innerParams =
-      GetParametersForInner(aTextRun, &flags, aRefContext);
+      GetParametersForInner(aTextRun, &flags, aRefDrawTarget);
 
   nsAutoPtr<nsTransformedTextRun> transformedChild;
   nsAutoPtr<gfxTextRun> cachedChild;
   gfxTextRun* child;
 
   if (mathVar == NS_MATHML_MATHVARIANT_BOLD && doMathvariantStyling) {
     font.style = NS_FONT_STYLE_NORMAL;
     font.weight = NS_FONT_WEIGHT_BOLD;
@@ -775,17 +775,17 @@ MathMLTextRunFactory::RebuildTextRun(nsT
     return;
   // Copy potential linebreaks into child so they're preserved
   // (and also child will be shaped appropriately)
   NS_ASSERTION(convertedString.Length() == canBreakBeforeArray.Length(),
                "Dropped characters or break-before values somewhere!");
   child->SetPotentialLineBreaks(0, canBreakBeforeArray.Length(),
                                 canBreakBeforeArray.Elements());
   if (transformedChild) {
-    transformedChild->FinishSettingProperties(aRefContext, aMFR);
+    transformedChild->FinishSettingProperties(aRefDrawTarget, aMFR);
   }
 
   if (mergeNeeded) {
     // Now merge multiple characters into one multi-glyph character as required
     NS_ASSERTION(charsToMergeArray.Length() == child->GetLength(),
                  "source length mismatch");
     NS_ASSERTION(deletedCharsArray.Length() == aTextRun->GetLength(),
                  "destination length mismatch");
--- a/layout/generic/MathMLTextRunFactory.h
+++ b/layout/generic/MathMLTextRunFactory.h
@@ -17,17 +17,17 @@ public:
                        uint32_t aFlags, uint8_t aSSTYScriptLevel,
                        float aFontInflation)
     : mInnerTransformingTextRunFactory(aInnerTransformingTextRunFactory),
       mFlags(aFlags),
       mFontInflation(aFontInflation),
       mSSTYScriptLevel(aSSTYScriptLevel) {}
 
   virtual void RebuildTextRun(nsTransformedTextRun* aTextRun,
-                              gfxContext* aRefContext,
+                              mozilla::gfx::DrawTarget* aRefDrawTarget,
                               gfxMissingFontRecorder* aMFR) override;
   enum {
     // Style effects which may override single character <mi> behaviour
     MATH_FONT_STYLING_NORMAL   = 0x1, // fontstyle="normal" has been set.
     MATH_FONT_WEIGHT_BOLD      = 0x2, // fontweight="bold" has been set.
     MATH_FONT_FEATURE_DTLS     = 0x4, // font feature dtls should be set
   };
 
--- a/layout/generic/TextOverflow.cpp
+++ b/layout/generic/TextOverflow.cpp
@@ -23,40 +23,45 @@
 #include "nsIFrameInlines.h"
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/Likely.h"
 #include "nsISelection.h"
 
 namespace mozilla {
 namespace css {
 
-class LazyReferenceRenderingContextGetterFromFrame final :
-    public gfxFontGroup::LazyReferenceContextGetter {
+class LazyReferenceRenderingDrawTargetGetterFromFrame final :
+    public gfxFontGroup::LazyReferenceDrawTargetGetter {
 public:
-  explicit LazyReferenceRenderingContextGetterFromFrame(nsIFrame* aFrame)
+  typedef mozilla::gfx::DrawTarget DrawTarget;
+
+  explicit LazyReferenceRenderingDrawTargetGetterFromFrame(nsIFrame* aFrame)
     : mFrame(aFrame) {}
-  virtual already_AddRefed<gfxContext> GetRefContext() override
+  virtual already_AddRefed<DrawTarget> GetRefDrawTarget() override
   {
-    return mFrame->PresContext()->PresShell()->CreateReferenceRenderingContext();
+    RefPtr<gfxContext> ctx =
+      mFrame->PresContext()->PresShell()->CreateReferenceRenderingContext();
+    RefPtr<DrawTarget> dt = ctx->GetDrawTarget();
+    return dt.forget();
   }
 private:
   nsIFrame* mFrame;
 };
 
 static gfxTextRun*
 GetEllipsisTextRun(nsIFrame* aFrame)
 {
   RefPtr<nsFontMetrics> fm;
   nsLayoutUtils::GetFontMetricsForFrame(aFrame, getter_AddRefs(fm),
     nsLayoutUtils::FontSizeInflationFor(aFrame));
-  LazyReferenceRenderingContextGetterFromFrame lazyRefContextGetter(aFrame);
+  LazyReferenceRenderingDrawTargetGetterFromFrame lazyRefDrawTargetGetter(aFrame);
   return fm->GetThebesFontGroup()->GetEllipsisTextRun(
     aFrame->PresContext()->AppUnitsPerDevPixel(),
     nsLayoutUtils::GetTextRunOrientFlagsForStyle(aFrame->StyleContext()),
-    lazyRefContextGetter);
+    lazyRefDrawTargetGetter);
 }
 
 static nsIFrame*
 GetSelfOrNearestBlock(nsIFrame* aFrame)
 {
   return nsLayoutUtils::GetAsBlock(aFrame) ? aFrame :
          nsLayoutUtils::FindNearestBlockAncestor(aFrame);
 }
--- a/layout/generic/nsBlockFrame.cpp
+++ b/layout/generic/nsBlockFrame.cpp
@@ -838,23 +838,23 @@ nsBlockFrame::GetPrefISize(nsRenderingCo
   }
   data.ForceBreak();
 
   mPrefWidth = data.prevLines;
   return mPrefWidth;
 }
 
 nsRect
-nsBlockFrame::ComputeTightBounds(gfxContext* aContext) const
+nsBlockFrame::ComputeTightBounds(DrawTarget* aDrawTarget) const
 {
   // be conservative
   if (StyleContext()->HasTextDecorationLines()) {
     return GetVisualOverflowRect();
   }
-  return ComputeSimpleTightBounds(aContext);
+  return ComputeSimpleTightBounds(aDrawTarget);
 }
 
 /* virtual */ nsresult
 nsBlockFrame::GetPrefWidthTightBounds(nsRenderingContext* aRenderingContext,
                                       nscoord* aX,
                                       nscoord* aXMost)
 {
   nsIFrame* firstInFlow = FirstContinuation();
--- a/layout/generic/nsBlockFrame.h
+++ b/layout/generic/nsBlockFrame.h
@@ -225,17 +225,17 @@ public:
 
   virtual void MarkIntrinsicISizesDirty() override;
 private:
   void CheckIntrinsicCacheAgainstShrinkWrapState();
 public:
   virtual nscoord GetMinISize(nsRenderingContext *aRenderingContext) override;
   virtual nscoord GetPrefISize(nsRenderingContext *aRenderingContext) override;
 
-  virtual nsRect ComputeTightBounds(gfxContext* aContext) const override;
+  virtual nsRect ComputeTightBounds(DrawTarget* aDrawTarget) const override;
 
   virtual nsresult GetPrefWidthTightBounds(nsRenderingContext* aContext,
                                            nscoord* aX,
                                            nscoord* aXMost) override;
 
   /**
    * Compute the final block size of this frame.
    *
--- a/layout/generic/nsBulletFrame.cpp
+++ b/layout/generic/nsBulletFrame.cpp
@@ -603,18 +603,17 @@ nsBulletFrame::GetDesiredSize(nsPresCont
       }
       AppendSpacingToPadding(fm, aPadding);
       break;
 
     default:
       GetListItemText(text);
       finalSize.BSize(wm) = fm->MaxHeight();
       finalSize.ISize(wm) =
-        nsLayoutUtils::AppUnitWidthOfStringBidi(text, this, *fm,
-                                                *aRenderingContext);
+        nsLayoutUtils::AppUnitWidthOfStringBidi(text, this, *fm, *aRenderingContext);
       aMetrics.SetBlockStartAscent(wm.IsLineInverted()
                                      ? fm->MaxDescent() : fm->MaxAscent());
       break;
   }
   aMetrics.SetSize(wm, finalSize);
 }
 
 void
@@ -626,18 +625,18 @@ nsBulletFrame::Reflow(nsPresContext* aPr
   MarkInReflow();
   DO_GLOBAL_REFLOW_COUNT("nsBulletFrame");
   DISPLAY_REFLOW(aPresContext, this, aReflowState, aMetrics, aStatus);
 
   float inflation = nsLayoutUtils::FontSizeInflationFor(this);
   SetFontSizeInflation(inflation);
 
   // Get the base size
-  GetDesiredSize(aPresContext, aReflowState.rendContext,
-                 aMetrics, inflation, &mPadding);
+  GetDesiredSize(aPresContext, aReflowState.rendContext, aMetrics, inflation,
+                 &mPadding);
 
   // Add in the border and padding; split the top/bottom between the
   // ascent and descent to make things look nice
   WritingMode wm = aReflowState.GetWritingMode();
   const LogicalMargin& bp = aReflowState.ComputedLogicalBorderPadding();
   mPadding.BStart(wm) += NSToCoordRound(bp.BStart(wm) * inflation);
   mPadding.IEnd(wm) += NSToCoordRound(bp.IEnd(wm) * inflation);
   mPadding.BEnd(wm) += NSToCoordRound(bp.BEnd(wm) * inflation);
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -4517,39 +4517,39 @@ nsFrame::ComputeSize(nsRenderingContext 
 
   result.ISize(aWM) = std::max(0, result.ISize(aWM));
   result.BSize(aWM) = std::max(0, result.BSize(aWM));
 
   return result;
 }
 
 nsRect
-nsIFrame::ComputeTightBounds(gfxContext* aContext) const
+nsIFrame::ComputeTightBounds(DrawTarget* aDrawTarget) const
 {
   return GetVisualOverflowRect();
 }
 
 nsRect
-nsFrame::ComputeSimpleTightBounds(gfxContext* aContext) const
+nsFrame::ComputeSimpleTightBounds(DrawTarget* aDrawTarget) const
 {
   if (StyleOutline()->GetOutlineStyle() != NS_STYLE_BORDER_STYLE_NONE ||
       StyleBorder()->HasBorder() || !StyleBackground()->IsTransparent() ||
       StyleDisplay()->mAppearance) {
     // Not necessarily tight, due to clipping, negative
     // outline-offset, and lots of other issues, but that's OK
     return GetVisualOverflowRect();
   }
 
   nsRect r(0, 0, 0, 0);
   ChildListIterator lists(this);
   for (; !lists.IsDone(); lists.Next()) {
     nsFrameList::Enumerator childFrames(lists.CurrentList());
     for (; !childFrames.AtEnd(); childFrames.Next()) {
       nsIFrame* child = childFrames.get();
-      r.UnionRect(r, child->ComputeTightBounds(aContext) + child->GetPosition());
+      r.UnionRect(r, child->ComputeTightBounds(aDrawTarget) + child->GetPosition());
     }
   }
   return r;
 }
 
 /* virtual */ nsresult
 nsIFrame::GetPrefWidthTightBounds(nsRenderingContext* aContext,
                                   nscoord* aX,
--- a/layout/generic/nsFrame.h
+++ b/layout/generic/nsFrame.h
@@ -268,17 +268,17 @@ public:
               nscoord aAvailableISize,
               const mozilla::LogicalSize& aMargin,
               const mozilla::LogicalSize& aBorder,
               const mozilla::LogicalSize& aPadding,
               ComputeSizeFlags aFlags) override;
 
   // Compute tight bounds assuming this frame honours its border, background
   // and outline, its children's tight bounds, and nothing else.
-  nsRect ComputeSimpleTightBounds(gfxContext* aContext) const;
+  nsRect ComputeSimpleTightBounds(mozilla::gfx::DrawTarget* aDrawTarget) const;
   
   /**
    * A helper, used by |nsFrame::ComputeSize| (for frames that need to
    * override only this part of ComputeSize), that computes the size
    * that should be returned when 'width', 'height', and
    * min/max-width/height are all 'auto' or equivalent.
    *
    * In general, frames that can accept any computed width/height should
--- a/layout/generic/nsIFrame.h
+++ b/layout/generic/nsIFrame.h
@@ -418,16 +418,17 @@ public:
   typedef mozilla::FramePropertyDescriptor FramePropertyDescriptor;
   typedef mozilla::FrameProperties FrameProperties;
   typedef mozilla::layers::Layer Layer;
   typedef mozilla::layout::FrameChildList ChildList;
   typedef mozilla::layout::FrameChildListID ChildListID;
   typedef mozilla::layout::FrameChildListIDs ChildListIDs;
   typedef mozilla::layout::FrameChildListIterator ChildListIterator;
   typedef mozilla::layout::FrameChildListArrayIterator ChildListArrayIterator;
+  typedef mozilla::gfx::DrawTarget DrawTarget;
   typedef mozilla::gfx::Matrix Matrix;
   typedef mozilla::gfx::Matrix4x4 Matrix4x4;
   typedef mozilla::Sides Sides;
   typedef mozilla::LogicalSides LogicalSides;
 
   NS_DECL_QUERYFRAME_TARGET(nsIFrame)
 
   nsPresContext* PresContext() const {
@@ -889,18 +890,17 @@ public:
 
   NS_DECLARE_FRAME_PROPERTY(UsedMarginProperty, DeleteValue<nsMargin>)
   NS_DECLARE_FRAME_PROPERTY(UsedPaddingProperty, DeleteValue<nsMargin>)
   NS_DECLARE_FRAME_PROPERTY(UsedBorderProperty, DeleteValue<nsMargin>)
 
   NS_DECLARE_FRAME_PROPERTY(LineBaselineOffset, nullptr)
 
   NS_DECLARE_FRAME_PROPERTY(CachedBackgroundImage, ReleaseValue<gfxASurface>)
-  NS_DECLARE_FRAME_PROPERTY(CachedBackgroundImageDT,
-                            ReleaseValue<mozilla::gfx::DrawTarget>)
+  NS_DECLARE_FRAME_PROPERTY(CachedBackgroundImageDT, ReleaseValue<DrawTarget>)
 
   NS_DECLARE_FRAME_PROPERTY(InvalidationRect, DeleteValue<nsRect>)
 
   NS_DECLARE_FRAME_PROPERTY(RefusedAsyncAnimationProperty, nullptr)
 
   NS_DECLARE_FRAME_PROPERTY(GenConProperty, DestroyContentArray)
 
   nsTArray<nsIContent*>* GetGenConPseudos() {
@@ -1794,20 +1794,20 @@ public:
    * that encloses the pixels that are actually drawn. We're allowed to be
    * conservative and currently we don't try very hard. The rectangle is
    * in appunits and relative to the origin of this frame.
    *
    * This probably only needs to include frame bounds, glyph bounds, and
    * text decorations, but today it sometimes includes other things that
    * contribute to visual overflow.
    *
-   * @param aContext a rendering context that can be used if we need
+   * @param aDrawTarget a draw target that can be used if we need
    * to do measurement
    */
-  virtual nsRect ComputeTightBounds(gfxContext* aContext) const;
+  virtual nsRect ComputeTightBounds(DrawTarget* aDrawTarget) const;
 
   /**
    * This function is similar to GetPrefISize and ComputeTightBounds: it
    * computes the left and right coordinates of a preferred tight bounding
    * rectangle for the frame. This is a rectangle that would enclose the pixels
    * that are drawn if we lay out the element without taking any optional line
    * breaks. The rectangle is in appunits and relative to the origin of this
    * frame. Currently, this function is only implemented for nsBlockFrame and
--- a/layout/generic/nsImageFrame.cpp
+++ b/layout/generic/nsImageFrame.cpp
@@ -1198,17 +1198,18 @@ nsImageFrame::DisplayAltText(nsPresConte
         } else {
           x = aRect.XMost() - strWidth;
           dir = NSBIDI_RTL;
         }
       }
 
       rv = nsBidiPresUtils::RenderText(str, maxFit, dir,
                                        aPresContext, aRenderingContext,
-                                       aRenderingContext, *fm, x, y);
+                                       aRenderingContext.GetDrawTarget(),
+                                       *fm, x, y);
     }
     if (NS_FAILED(rv)) {
       nsLayoutUtils::DrawUniDirString(str, maxFit,
                                       isVertical
                                         ? nsPoint(pt.x + maxDescent, pt.y)
                                         : nsPoint(pt.x, pt.y + maxAscent),
                                       *fm, aRenderingContext);
     }
--- a/layout/generic/nsInlineFrame.cpp
+++ b/layout/generic/nsInlineFrame.cpp
@@ -287,23 +287,23 @@ nsInlineFrame::ComputeSize(nsRenderingCo
                            const LogicalSize& aPadding,
                            ComputeSizeFlags aFlags)
 {
   // Inlines and text don't compute size before reflow.
   return LogicalSize(aWM, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE);
 }
 
 nsRect
-nsInlineFrame::ComputeTightBounds(gfxContext* aContext) const
+nsInlineFrame::ComputeTightBounds(DrawTarget* aDrawTarget) const
 {
   // be conservative
   if (StyleContext()->HasTextDecorationLines()) {
     return GetVisualOverflowRect();
   }
-  return ComputeSimpleTightBounds(aContext);
+  return ComputeSimpleTightBounds(aDrawTarget);
 }
 
 void
 nsInlineFrame::ReparentFloatsForInlineChild(nsIFrame* aOurLineContainer,
                                             nsIFrame* aFrame,
                                             bool aReparentSiblings)
 {
   // XXXbz this would be better if it took a nsFrameList or a frame
--- a/layout/generic/nsInlineFrame.h
+++ b/layout/generic/nsInlineFrame.h
@@ -75,17 +75,17 @@ public:
   ComputeSize(nsRenderingContext *aRenderingContext,
               mozilla::WritingMode aWritingMode,
               const mozilla::LogicalSize& aCBSize,
               nscoord aAvailableISize,
               const mozilla::LogicalSize& aMargin,
               const mozilla::LogicalSize& aBorder,
               const mozilla::LogicalSize& aPadding,
               ComputeSizeFlags aFlags) override;
-  virtual nsRect ComputeTightBounds(gfxContext* aContext) const override;
+  virtual nsRect ComputeTightBounds(DrawTarget* aDrawTarget) const override;
   virtual void Reflow(nsPresContext* aPresContext,
                       nsHTMLReflowMetrics& aDesiredSize,
                       const nsHTMLReflowState& aReflowState,
                       nsReflowStatus& aStatus) override;
 
   virtual nsresult AttributeChanged(int32_t aNameSpaceID,
                                     nsIAtom* aAttribute,
                                     int32_t aModType) override;
--- a/layout/generic/nsLineLayout.cpp
+++ b/layout/generic/nsLineLayout.cpp
@@ -938,17 +938,18 @@ nsLineLayout::ReflowFrame(nsIFrame* aFra
   nsIFrame* savedOptionalBreakFrame =
     GetLastOptionalBreakPosition(&savedOptionalBreakOffset,
                                  &savedOptionalBreakPriority);
 
   if (!isText) {
     aFrame->Reflow(mPresContext, metrics, *reflowStateHolder, aReflowStatus);
   } else {
     static_cast<nsTextFrame*>(aFrame)->
-      ReflowText(*this, availableSpaceOnLine, psd->mReflowState->rendContext,
+      ReflowText(*this, availableSpaceOnLine,
+                 psd->mReflowState->rendContext->GetDrawTarget(),
                  metrics, aReflowStatus);
   }
 
   pfd->mJustificationInfo = mJustificationInfo;
   mJustificationInfo = JustificationInfo();
 
   // See if the frame is a placeholderFrame and if it is process
   // the float. At the same time, check if the frame has any non-collapsed-away
@@ -2587,17 +2588,17 @@ nsLineLayout::TrimTrailingWhiteSpaceIn(P
       *aDeltaISize = 0;
       return true;
     }
     else if (pfd->mIsTextFrame) {
       // Call TrimTrailingWhiteSpace even on empty textframes because they
       // might have a soft hyphen which should now appear, changing the frame's
       // width
       nsTextFrame::TrimOutput trimOutput = static_cast<nsTextFrame*>(pfd->mFrame)->
-          TrimTrailingWhiteSpace(mBlockReflowState->rendContext);
+          TrimTrailingWhiteSpace(mBlockReflowState->rendContext->GetDrawTarget());
 #ifdef NOISY_TRIM
       nsFrame::ListTag(stdout, psd->mFrame->mFrame);
       printf(": trim of ");
       nsFrame::ListTag(stdout, pfd->mFrame);
       printf(" returned %d\n", trimOutput.mDeltaWidth);
 #endif
 
       if (trimOutput.mChanged) {
--- a/layout/generic/nsPageFrame.cpp
+++ b/layout/generic/nsPageFrame.cpp
@@ -328,33 +328,37 @@ nsPageFrame::DrawHeaderFooter(nsRenderin
                               const nsRect&        aRect,
                               nscoord              aAscent,
                               nscoord              aHeight,
                               nscoord              aWidth)
 {
 
   nscoord contentWidth = aWidth - (mPD->mEdgePaperMargin.left + mPD->mEdgePaperMargin.right);
 
+  gfxContext* gfx = aRenderingContext.ThebesContext();
+  DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
+
   if ((aHeaderFooter == eHeader && aHeight < mPD->mReflowMargin.top) ||
       (aHeaderFooter == eFooter && aHeight < mPD->mReflowMargin.bottom)) {
     nsAutoString str;
     ProcessSpecialCodes(aStr, str);
 
     int32_t indx;
     int32_t textWidth = 0;
     const char16_t* text = str.get();
 
     int32_t len = (int32_t)str.Length();
     if (len == 0) {
       return; // bail is empty string
     }
     // find how much text fits, the "position" is the size of the available area
-    if (nsLayoutUtils::BinarySearchForPosition(&aRenderingContext, aFontMetrics,
-                                               text, 0, 0, 0, len,
-                                int32_t(contentWidth), indx, textWidth)) {
+    if (nsLayoutUtils::BinarySearchForPosition(drawTarget, aFontMetrics, text,
+                                               0, 0, 0, len,
+                                               int32_t(contentWidth), indx,
+                                               textWidth)) {
       if (indx < len-1 ) {
         // we can't fit in all the text
         if (indx > 3) {
           // But we can fit in at least 4 chars.  Show all but 3 of them, then
           // an ellipsis.
           // XXXbz for non-plane0 text, this may be cutting things in the
           // middle of a codepoint!  Also, we have no guarantees that the three
           // dots will fit in the space the three chars we removed took up with
@@ -378,24 +382,21 @@ nsPageFrame::DrawHeaderFooter(nsRenderin
     nscoord x = GetXPosition(aRenderingContext, aFontMetrics, aRect, aJust, str);
     nscoord y;
     if (aHeaderFooter == eHeader) {
       y = aRect.y + mPD->mEdgePaperMargin.top;
     } else {
       y = aRect.YMost() - aHeight - mPD->mEdgePaperMargin.bottom;
     }
 
-    DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
-    gfxContext* gfx = aRenderingContext.ThebesContext();
-
     // set up new clip and draw the text
     gfx->Save();
     gfx->Clip(NSRectToSnappedRect(aRect, PresContext()->AppUnitsPerDevPixel(),
                                   *drawTarget));
-    aRenderingContext.ThebesContext()->SetColor(Color(0.f, 0.f, 0.f));
+    gfx->SetColor(Color(0.f, 0.f, 0.f));
     nsLayoutUtils::DrawString(this, aFontMetrics, &aRenderingContext,
                               str.get(), str.Length(),
                               nsPoint(x, y + aAscent));
     gfx->Restore();
   }
 }
 
 /**
--- a/layout/generic/nsRubyBaseContainerFrame.cpp
+++ b/layout/generic/nsRubyBaseContainerFrame.cpp
@@ -58,34 +58,33 @@ nsresult
 nsRubyBaseContainerFrame::GetFrameName(nsAString& aResult) const
 {
   return MakeFrameName(NS_LITERAL_STRING("RubyBaseContainer"), aResult);
 }
 #endif
 
 static gfxBreakPriority
 LineBreakBefore(nsIFrame* aFrame,
-                nsRenderingContext* aRenderingContext,
+                DrawTarget* aDrawTarget,
                 nsIFrame* aLineContainerFrame,
                 const nsLineList::iterator* aLine)
 {
   for (nsIFrame* child = aFrame; child;
        child = child->GetFirstPrincipalChild()) {
     if (!child->CanContinueTextRun()) {
       // It is not an inline element. We can break before it.
       return gfxBreakPriority::eNormalBreak;
     }
     if (child->GetType() != nsGkAtoms::textFrame) {
       continue;
     }
 
     auto textFrame = static_cast<nsTextFrame*>(child);
     gfxSkipCharsIterator iter =
-      textFrame->EnsureTextRun(nsTextFrame::eInflated,
-                               aRenderingContext->ThebesContext(),
+      textFrame->EnsureTextRun(nsTextFrame::eInflated, aDrawTarget,
                                aLineContainerFrame, aLine);
     iter.SetOriginalOffset(textFrame->GetContentOffset());
     uint32_t pos = iter.GetSkippedOffset();
     gfxTextRun* textRun = textFrame->GetTextRun(nsTextFrame::eInflated);
     if (pos >= textRun->GetLength()) {
       // The text frame contains no character at all.
       return gfxBreakPriority::eNoBreak;
     }
@@ -203,17 +202,18 @@ nsRubyBaseContainerFrame::AddInlineMinIS
   for (nsIFrame* frame = this; frame; frame = frame->GetNextInFlow()) {
     RubyColumnEnumerator enumerator(
       static_cast<nsRubyBaseContainerFrame*>(frame), textContainers);
     for (; !enumerator.AtEnd(); enumerator.Next()) {
       if (firstFrame ? allowInitialLineBreak : allowLineBreak) {
         nsIFrame* baseFrame = enumerator.GetFrameAtLevel(0);
         if (baseFrame) {
           gfxBreakPriority breakPriority =
-            LineBreakBefore(baseFrame, aRenderingContext, nullptr, nullptr);
+            LineBreakBefore(baseFrame, aRenderingContext->GetDrawTarget(),
+                            nullptr, nullptr);
           if (breakPriority != gfxBreakPriority::eNoBreak) {
             aData->OptionallyBreak();
           }
         }
       }
       firstFrame = false;
       nscoord isize = CalculateColumnPrefISize(aRenderingContext,
                                                enumerator, aData);
@@ -577,17 +577,17 @@ nsRubyBaseContainerFrame::ReflowOneColum
   const auto& textReflowStates = aReflowState.mTextReflowStates;
   nscoord istart = baseReflowState.mLineLayout->GetCurrentICoord();
 
   if (aColumn.mBaseFrame) {
     bool allowBreakBefore = aColumnIndex ?
       aReflowState.mAllowLineBreak : aReflowState.mAllowInitialLineBreak;
     if (allowBreakBefore) {
       gfxBreakPriority breakPriority = LineBreakBefore(
-        aColumn.mBaseFrame, baseReflowState.rendContext,
+        aColumn.mBaseFrame, baseReflowState.rendContext->GetDrawTarget(),
         baseReflowState.mLineLayout->LineContainerFrame(),
         baseReflowState.mLineLayout->GetLine());
       if (breakPriority != gfxBreakPriority::eNoBreak) {
         gfxBreakPriority lastBreakPriority =
           baseReflowState.mLineLayout->LastOptionalBreakPriority();
         if (breakPriority >= lastBreakPriority) {
           // Either we have been overflow, or we are forced
           // to break here, do break before.
--- a/layout/generic/nsTextFrame.cpp
+++ b/layout/generic/nsTextFrame.cpp
@@ -859,20 +859,20 @@ CreateObserversForAnimatedGlyphs(gfxText
  * line breaks, and font changes) and builds a gfxTextRun at each boundary.
  * It also detects linebreaker run boundaries (changes from text to non-text,
  * and hard line breaks) and at each boundary runs the linebreaker to compute
  * potential line breaks. It also records actual line breaks to store them in
  * the textruns.
  */
 class BuildTextRunsScanner {
 public:
-  BuildTextRunsScanner(nsPresContext* aPresContext, gfxContext* aContext,
+  BuildTextRunsScanner(nsPresContext* aPresContext, DrawTarget* aDrawTarget,
       nsIFrame* aLineContainer, nsTextFrame::TextRunType aWhichTextRun) :
     mCurrentFramesAllSameTextRun(nullptr),
-    mContext(aContext),
+    mDrawTarget(aDrawTarget),
     mLineContainer(aLineContainer),
     mMissingFonts(aPresContext->MissingFontRecorder()),
     mBidiEnabled(aPresContext->BidiEnabled()),
     mSkipIncompleteTextRuns(false),
     mWhichTextRun(aWhichTextRun),
     mNextRunContextInfo(nsTextFrameUtils::INCOMING_NONE),
     mCurrentRunContextInfo(nsTextFrameUtils::INCOMING_NONE) {
     ResetRunInfo();
@@ -962,20 +962,22 @@ public:
     int32_t GetContentEnd() {
       return mEndFrame ? mEndFrame->GetContentOffset()
           : mStartFrame->GetContent()->GetText()->GetLength();
     }
   };
 
   class BreakSink final : public nsILineBreakSink {
   public:
-    BreakSink(gfxTextRun* aTextRun, gfxContext* aContext,
-              uint32_t aOffsetIntoTextRun) :
-                mTextRun(aTextRun), mContext(aContext),
-                mOffsetIntoTextRun(aOffsetIntoTextRun) {}
+    BreakSink(gfxTextRun* aTextRun, DrawTarget* aDrawTarget,
+              uint32_t aOffsetIntoTextRun)
+      : mTextRun(aTextRun)
+      , mDrawTarget(aDrawTarget)
+      , mOffsetIntoTextRun(aOffsetIntoTextRun)
+    {}
 
     virtual void SetBreaks(uint32_t aOffset, uint32_t aLength,
                            uint8_t* aBreakBefore) override {
       if (mTextRun->SetPotentialLineBreaks(aOffset + mOffsetIntoTextRun, aLength,
                                            aBreakBefore)) {
         // Be conservative and assume that some breaks have been set
         mTextRun->ClearFlagBits(nsTextFrameUtils::TEXT_NO_BREAKS);
       }
@@ -996,37 +998,37 @@ public:
     void Finish(gfxMissingFontRecorder* aMFR) {
       MOZ_ASSERT(!(mTextRun->GetFlags() &
                    (gfxTextRunFactory::TEXT_UNUSED_FLAGS |
                     nsTextFrameUtils::TEXT_UNUSED_FLAG)),
                    "Flag set that should never be set! (memory safety error?)");
       if (mTextRun->GetFlags() & nsTextFrameUtils::TEXT_IS_TRANSFORMED) {
         nsTransformedTextRun* transformedTextRun =
           static_cast<nsTransformedTextRun*>(mTextRun);
-        transformedTextRun->FinishSettingProperties(mContext, aMFR);
+        transformedTextRun->FinishSettingProperties(mDrawTarget, aMFR);
       }
       // The way nsTransformedTextRun is implemented, its glyph runs aren't
       // available until after nsTransformedTextRun::FinishSettingProperties()
       // is called. So that's why we defer checking for animated glyphs to here.
       CreateObserversForAnimatedGlyphs(mTextRun);
     }
 
     gfxTextRun*  mTextRun;
-    gfxContext*  mContext;
+    DrawTarget*  mDrawTarget;
     uint32_t     mOffsetIntoTextRun;
   };
 
 private:
   nsAutoTArray<MappedFlow,10>   mMappedFlows;
   nsAutoTArray<nsTextFrame*,50> mLineBreakBeforeFrames;
   nsAutoTArray<nsAutoPtr<BreakSink>,10> mBreakSinks;
   nsAutoTArray<gfxTextRun*,5>   mTextRunsToDelete;
   nsLineBreaker                 mLineBreaker;
   gfxTextRun*                   mCurrentFramesAllSameTextRun;
-  gfxContext*                   mContext;
+  DrawTarget*                   mDrawTarget;
   nsIFrame*                     mLineContainer;
   nsTextFrame*                  mLastFrame;
   // The common ancestor of the current frame and the previous leaf frame
   // on the line, or null if there was no previous leaf frame.
   nsIFrame*                     mCommonAncestorWithLastFrame;
   gfxMissingFontRecorder*       mMissingFonts;
   // mMaxTextLength is an upper bound on the size of the text in all mapped frames
   // The value UINT32_MAX represents overflow; text will be discarded
@@ -1246,17 +1248,17 @@ BuildTextRunsScanner::FindBoundaries(nsI
  *        we'll walk the ancestors to find it.  It's required to be non-null
  *        when aForFrameLine is non-null.
  * @param aForFrameLine the line containing aForFrame; if null, we'll figure
  *        out the line (slowly)
  * @param aWhichTextRun The type of text run we want to build. If font inflation
  *        is enabled, this will be eInflated, otherwise it's eNotInflated.
  */
 static void
-BuildTextRuns(gfxContext* aContext, nsTextFrame* aForFrame,
+BuildTextRuns(DrawTarget* aDrawTarget, nsTextFrame* aForFrame,
               nsIFrame* aLineContainer,
               const nsLineList::iterator* aForFrameLine,
               nsTextFrame::TextRunType aWhichTextRun)
 {
   MOZ_ASSERT(aForFrame, "for no frame?");
   NS_ASSERTION(!aForFrameLine || aLineContainer,
                "line but no line container");
   
@@ -1280,18 +1282,18 @@ BuildTextRuns(gfxContext* aContext, nsTe
       aLineContainer->AddStateBits(NS_FRAME_IS_IN_SINGLE_CHAR_MI);
     }
   }
   if (aForFrame->HasAnyStateBits(NS_FRAME_MATHML_SCRIPT_DESCENDANT)) {
     aLineContainer->AddStateBits(NS_FRAME_MATHML_SCRIPT_DESCENDANT);
   }
 
   nsPresContext* presContext = aLineContainer->PresContext();
-  BuildTextRunsScanner scanner(presContext, aContext, aLineContainer,
-                               aWhichTextRun);
+  BuildTextRunsScanner scanner(presContext, aDrawTarget,
+                               aLineContainer, aWhichTextRun);
 
   nsBlockFrame* block = nsLayoutUtils::GetAsBlock(aLineContainer);
 
   if (!block) {
     nsIFrame* textRunContainer = aLineContainer;
     if (aLineContainer->GetType() == nsGkAtoms::rubyTextContainerFrame) {
       textRunContainer = aForFrame;
       while (textRunContainer &&
@@ -1836,37 +1838,42 @@ GetFontGroupForFrame(nsIFrame* aFrame, f
   }
   // XXX this is a bit bogus, we're releasing 'metrics' so the
   // returned font-group might actually be torn down, although because
   // of the way the device context caches font metrics, this seems to
   // not actually happen. But we should fix this.
   return metrics->GetThebesFontGroup();
 }
 
-static already_AddRefed<gfxContext>
-CreateReferenceThebesContext(nsTextFrame* aTextFrame)
-{
-  return aTextFrame->PresContext()->PresShell()->CreateReferenceRenderingContext();
+static already_AddRefed<DrawTarget>
+CreateReferenceDrawTarget(nsTextFrame* aTextFrame)
+{
+  RefPtr<gfxContext> ctx =
+    aTextFrame->PresContext()->PresShell()->CreateReferenceRenderingContext();
+  RefPtr<DrawTarget> dt = ctx->GetDrawTarget();
+  return dt.forget();
 }
 
 /**
  * The returned textrun must be deleted when no longer needed.
  */
 static gfxTextRun*
-GetHyphenTextRun(gfxTextRun* aTextRun, gfxContext* aContext, nsTextFrame* aTextFrame)
-{
-  RefPtr<gfxContext> ctx = aContext;
-  if (!ctx) {
-    ctx = CreateReferenceThebesContext(aTextFrame);
-  }
-  if (!ctx)
-    return nullptr;
+GetHyphenTextRun(gfxTextRun* aTextRun, DrawTarget* aDrawTarget,
+                 nsTextFrame* aTextFrame)
+{
+  RefPtr<DrawTarget> dt = aDrawTarget;
+  if (!dt) {
+    dt = CreateReferenceDrawTarget(aTextFrame);
+    if (!dt) {
+      return nullptr;
+    }
+  }
 
   return aTextRun->GetFontGroup()->
-    MakeHyphenTextRun(ctx, aTextRun->GetAppUnitsPerDevUnit());
+    MakeHyphenTextRun(dt, aTextRun->GetAppUnitsPerDevUnit());
 }
 
 PR_STATIC_ASSERT(NS_STYLE_WHITESPACE_NORMAL == 0);
 PR_STATIC_ASSERT(NS_STYLE_WHITESPACE_PRE == 1);
 PR_STATIC_ASSERT(NS_STYLE_WHITESPACE_NOWRAP == 2);
 PR_STATIC_ASSERT(NS_STYLE_WHITESPACE_PRE_WRAP == 3);
 PR_STATIC_ASSERT(NS_STYLE_WHITESPACE_PRE_LINE == 4);
 PR_STATIC_ASSERT(NS_STYLE_WHITESPACE_PRE_SPACE == 5);
@@ -2212,17 +2219,17 @@ BuildTextRunsScanner::BuildTextRunForFra
     }
     textFlags |= nsTextFrameUtils::TEXT_IS_TRANSFORMED;
     NS_ASSERTION(iter.GetSkippedOffset() == transformedLength,
                  "We didn't cover all the characters in the text run!");
   }
 
   gfxTextRun* textRun;
   gfxTextRunFactory::Parameters params =
-      { mContext, finalUserData, &skipChars,
+      { mDrawTarget, finalUserData, &skipChars,
         textBreakPointsAfterTransform.Elements(),
         uint32_t(textBreakPointsAfterTransform.Length()),
         int32_t(firstFrame->PresContext()->AppUnitsPerDevPixel())};
 
   if (mDoubleByteText) {
     const char16_t* text = static_cast<const char16_t*>(textPtr);
     if (transformingFactory) {
       textRun = transformingFactory->MakeTextRun(text, transformedLength,
@@ -2443,17 +2450,17 @@ BuildTextRunsScanner::SetupBreakSinksFor
   for (uint32_t i = 0; i < mMappedFlows.Length(); ++i) {
     MappedFlow* mappedFlow = &mMappedFlows[i];
     uint32_t offset = iter.GetSkippedOffset();
     gfxSkipCharsIterator iterNext = iter;
     iterNext.AdvanceOriginal(mappedFlow->GetContentEnd() -
             mappedFlow->mStartFrame->GetContentOffset());
 
     nsAutoPtr<BreakSink>* breakSink =
-      mBreakSinks.AppendElement(new BreakSink(aTextRun, mContext, offset));
+      mBreakSinks.AppendElement(new BreakSink(aTextRun, mDrawTarget, offset));
     if (!breakSink || !*breakSink)
       return;
 
     uint32_t length = iterNext.GetSkippedOffset() - offset;
     uint32_t flags = 0;
     nsIFrame* initialBreakController = mappedFlow->mAncestorControllingInitialBreak;
     if (!initialBreakController) {
       initialBreakController = mLineContainer;
@@ -2689,33 +2696,33 @@ BuildTextRunsScanner::AssignTextRun(gfxT
 }
 
 NS_QUERYFRAME_HEAD(nsTextFrame)
   NS_QUERYFRAME_ENTRY(nsTextFrame)
 NS_QUERYFRAME_TAIL_INHERITING(nsTextFrameBase)
 
 gfxSkipCharsIterator
 nsTextFrame::EnsureTextRun(TextRunType aWhichTextRun,
-                           gfxContext* aReferenceContext,
+                           DrawTarget* aRefDrawTarget,
                            nsIFrame* aLineContainer,
                            const nsLineList::iterator* aLine,
                            uint32_t* aFlowEndInTextRun)
 {
   gfxTextRun *textRun = GetTextRun(aWhichTextRun);
   if (textRun && (!aLine || !(*aLine)->GetInvalidateTextRuns())) {
     if (textRun->GetExpirationState()->IsTracked()) {
       gTextRuns->MarkUsed(textRun);
     }
   } else {
-    RefPtr<gfxContext> ctx = aReferenceContext;
-    if (!ctx) {
-      ctx = CreateReferenceThebesContext(this);
-    }
-    if (ctx) {
-      BuildTextRuns(ctx, this, aLineContainer, aLine, aWhichTextRun);
+    RefPtr<DrawTarget> refDT = aRefDrawTarget;
+    if (!refDT) {
+      refDT = CreateReferenceDrawTarget(this);
+    }
+    if (refDT) {
+      BuildTextRuns(refDT, this, aLineContainer, aLine, aWhichTextRun);
     }
     textRun = GetTextRun(aWhichTextRun);
     if (!textRun) {
       // A text run was not constructed for this frame. This is bad. The caller
       // will check mTextRun.
       static const gfxSkipChars emptySkipChars;
       return gfxSkipCharsIterator(emptySkipChars, 0);
     }
@@ -2995,18 +3002,18 @@ public:
   virtual void GetSpacing(uint32_t aStart, uint32_t aLength, Spacing* aSpacing);
   virtual gfxFloat GetHyphenWidth();
   virtual void GetHyphenationBreaks(uint32_t aStart, uint32_t aLength,
                                     bool* aBreakBefore);
   virtual int8_t GetHyphensOption() {
     return mTextStyle->mHyphens;
   }
 
-  virtual already_AddRefed<gfxContext> GetContext() {
-    return CreateReferenceThebesContext(GetFrame());
+  virtual already_AddRefed<DrawTarget> GetDrawTarget() {
+    return CreateReferenceDrawTarget(GetFrame());
   }
 
   virtual uint32_t GetAppUnitsPerDevUnit() {
     return mTextRun->GetAppUnitsPerDevUnit();
   }
 
   void GetSpacingInternal(uint32_t aStart, uint32_t aLength, Spacing* aSpacing,
                           bool aIgnoreTabs);
@@ -5117,27 +5124,27 @@ GetInflationForTextDecorations(nsIFrame*
   return nsLayoutUtils::FontSizeInflationInner(aFrame, aInflationMinFontSize);
 }
 
 static gfxTextRun*
 GenerateTextRunForEmphasisMarks(nsTextFrame* aFrame, nsFontMetrics* aFontMetrics,
                                 WritingMode aWM, const nsStyleText* aStyleText)
 {
   const nsString& emphasisString = aStyleText->mTextEmphasisStyleString;
-  RefPtr<gfxContext> ctx = CreateReferenceThebesContext(aFrame);
+  RefPtr<DrawTarget> dt = CreateReferenceDrawTarget(aFrame);
   auto appUnitsPerDevUnit = aFrame->PresContext()->AppUnitsPerDevPixel();
   uint32_t flags = nsLayoutUtils::
     GetTextRunOrientFlagsForStyle(aFrame->StyleContext());
   if (flags == gfxTextRunFactory::TEXT_ORIENT_VERTICAL_MIXED) {
     // The emphasis marks should always be rendered upright per spec.
     flags = gfxTextRunFactory::TEXT_ORIENT_VERTICAL_UPRIGHT;
   }
   return aFontMetrics->GetThebesFontGroup()->
     MakeTextRun<char16_t>(emphasisString.get(), emphasisString.Length(),
-                          ctx, appUnitsPerDevUnit, flags, nullptr);
+                          dt, appUnitsPerDevUnit, flags, nullptr);
 }
 
 static nsRubyFrame*
 FindRubyAncestor(nsTextFrame* aFrame)
 {
   for (nsIFrame* frame = aFrame->GetParent();
        frame && frame->IsFrameOfType(nsIFrame::eLineParticipant);
        frame = frame->GetParent()) {
@@ -5804,27 +5811,27 @@ bool SelectionIterator::GetNextSegment(g
   *aStyle = style;
   return true;
 }
 
 static void
 AddHyphenToMetrics(nsTextFrame* aTextFrame, gfxTextRun* aBaseTextRun,
                    gfxTextRun::Metrics* aMetrics,
                    gfxFont::BoundingBoxType aBoundingBoxType,
-                   gfxContext* aContext)
+                   DrawTarget* aDrawTarget)
 {
   // Fix up metrics to include hyphen
   nsAutoPtr<gfxTextRun> hyphenTextRun(
-    GetHyphenTextRun(aBaseTextRun, aContext, aTextFrame));
+    GetHyphenTextRun(aBaseTextRun, aDrawTarget, aTextFrame));
   if (!hyphenTextRun.get())
     return;
 
   gfxTextRun::Metrics hyphenMetrics =
-    hyphenTextRun->MeasureText(0, hyphenTextRun->GetLength(),
-                               aBoundingBoxType, aContext, nullptr);
+    hyphenTextRun->MeasureText(0, hyphenTextRun->GetLength(), aBoundingBoxType,
+                               aDrawTarget, nullptr);
   if (aTextFrame->GetWritingMode().IsLineInverted()) {
     hyphenMetrics.mBoundingBox.y = -hyphenMetrics.mBoundingBox.YMost();
   }
   aMetrics->CombineWith(hyphenMetrics, aBaseTextRun->IsRightToLeft());
 }
 
 void
 nsTextFrame::PaintOneShadow(uint32_t aOffset, uint32_t aLength,
@@ -6415,17 +6422,17 @@ nsTextFrame::PaintShadows(nsCSSShadowArr
     mTextRun->MeasureText(aOffset, aLength, gfxFont::LOOSE_INK_EXTENTS,
                           nullptr, &aProvider);
   if (GetWritingMode().IsLineInverted()) {
     Swap(shadowMetrics.mAscent, shadowMetrics.mDescent);
     shadowMetrics.mBoundingBox.y = -shadowMetrics.mBoundingBox.YMost();
   }
   if (GetStateBits() & TEXT_HYPHEN_BREAK) {
     AddHyphenToMetrics(this, mTextRun, &shadowMetrics,
-                       gfxFont::LOOSE_INK_EXTENTS, aCtx);
+                       gfxFont::LOOSE_INK_EXTENTS, aCtx->GetDrawTarget());
   }
   // Add bounds of text decorations
   gfxRect decorationRect(0, -shadowMetrics.mAscent,
       shadowMetrics.mAdvanceWidth, shadowMetrics.mAscent + shadowMetrics.mDescent);
   shadowMetrics.mBoundingBox.UnionRect(shadowMetrics.mBoundingBox,
                                        decorationRect);
 
   // If the textrun uses any color or SVG fonts, we need to force use of a mask
@@ -7800,20 +7807,19 @@ void nsTextFrame::MarkIntrinsicISizesDir
 // XXX this doesn't handle characters shaped by line endings. We need to
 // temporarily override the "current line ending" settings.
 void
 nsTextFrame::AddInlineMinISizeForFlow(nsRenderingContext *aRenderingContext,
                                       nsIFrame::InlineMinISizeData *aData,
                                       TextRunType aTextRunType)
 {
   uint32_t flowEndInTextRun;
-  gfxContext* ctx = aRenderingContext->ThebesContext();
   gfxSkipCharsIterator iter =
-    EnsureTextRun(aTextRunType, ctx, aData->LineContainer(),
-                  aData->line, &flowEndInTextRun);
+    EnsureTextRun(aTextRunType, aRenderingContext->GetDrawTarget(),
+                  aData->LineContainer(), aData->line, &flowEndInTextRun);
   gfxTextRun *textRun = GetTextRun(aTextRunType);
   if (!textRun)
     return;
 
   // Pass null for the line container. This will disable tab spacing, but that's
   // OK since we can't really handle tabs for intrinsic sizing anyway.
   const nsStyleText* textStyle = StyleText();
   const nsTextFragment* frag = mContent->GetText();
@@ -7977,20 +7983,19 @@ nsTextFrame::AddInlineMinISize(nsRenderi
 // XXX this doesn't handle characters shaped by line endings. We need to
 // temporarily override the "current line ending" settings.
 void
 nsTextFrame::AddInlinePrefISizeForFlow(nsRenderingContext *aRenderingContext,
                                        nsIFrame::InlinePrefISizeData *aData,
                                        TextRunType aTextRunType)
 {
   uint32_t flowEndInTextRun;
-  gfxContext* ctx = aRenderingContext->ThebesContext();
   gfxSkipCharsIterator iter =
-    EnsureTextRun(aTextRunType, ctx, aData->LineContainer(),
-                  aData->line, &flowEndInTextRun);
+    EnsureTextRun(aTextRunType, aRenderingContext->GetDrawTarget(),
+                  aData->LineContainer(), aData->line, &flowEndInTextRun);
   gfxTextRun *textRun = GetTextRun(aTextRunType);
   if (!textRun)
     return;
 
   // Pass null for the line container. This will disable tab spacing, but that's
   // OK since we can't really handle tabs for intrinsic sizing anyway.
   
   const nsStyleText* textStyle = StyleText();
@@ -8139,17 +8144,17 @@ RoundOut(const gfxRect& aRect)
   r.x = NSToCoordFloor(aRect.X());
   r.y = NSToCoordFloor(aRect.Y());
   r.width = NSToCoordCeil(aRect.XMost()) - r.x;
   r.height = NSToCoordCeil(aRect.YMost()) - r.y;
   return r;
 }
 
 nsRect
-nsTextFrame::ComputeTightBounds(gfxContext* aContext) const
+nsTextFrame::ComputeTightBounds(DrawTarget* aDrawTarget) const
 {
   if (StyleContext()->HasTextDecorationLines() ||
       (GetStateBits() & TEXT_HYPHEN_BREAK)) {
     // This is conservative, but OK.
     return GetVisualOverflowRect();
   }
 
   gfxSkipCharsIterator iter =
@@ -8161,17 +8166,17 @@ nsTextFrame::ComputeTightBounds(gfxConte
                             nsTextFrame::eInflated);
   // Trim trailing whitespace
   provider.InitializeForDisplay(true);
 
   gfxTextRun::Metrics metrics =
         mTextRun->MeasureText(provider.GetStart().GetSkippedOffset(),
                               ComputeTransformedLength(provider),
                               gfxFont::TIGHT_HINTED_OUTLINE_EXTENTS,
-                              aContext, &provider);
+                              aDrawTarget, &provider);
   if (GetWritingMode().IsLineInverted()) {
     metrics.mBoundingBox.y = -metrics.mBoundingBox.YMost();
   }
   // mAscent should be the same as metrics.mAscent, but it's what we use to
   // paint so that's the one we'll use.
   nsRect boundingBox = RoundOut(metrics.mBoundingBox);
   boundingBox += nsPoint(0, mAscent);
   if (mTextRun->IsVertical()) {
@@ -8195,17 +8200,17 @@ nsTextFrame::GetPrefWidthTightBounds(nsR
   PropertyProvider provider(const_cast<nsTextFrame*>(this), iter,
                             nsTextFrame::eInflated);
   provider.InitializeForMeasure();
 
   gfxTextRun::Metrics metrics =
         mTextRun->MeasureText(provider.GetStart().GetSkippedOffset(),
                               ComputeTransformedLength(provider),
                               gfxFont::TIGHT_HINTED_OUTLINE_EXTENTS,
-                              aContext->ThebesContext(), &provider);
+                              aContext->GetDrawTarget(), &provider);
   // Round it like nsTextFrame::ComputeTightBounds() to ensure consistency.
   *aX = NSToCoordFloor(metrics.mBoundingBox.x);
   *aXMost = NSToCoordCeil(metrics.mBoundingBox.XMost());
 
   return NS_OK;
 }
 
 static bool
@@ -8442,17 +8447,17 @@ nsTextFrame::Reflow(nsPresContext*      
   // but not inside a cell. For now, just don't reflow.
   if (!aReflowState.mLineLayout) {
     ClearMetrics(aMetrics);
     aStatus = NS_FRAME_COMPLETE;
     return;
   }
 
   ReflowText(*aReflowState.mLineLayout, aReflowState.AvailableWidth(),
-             aReflowState.rendContext, aMetrics, aStatus);
+             aReflowState.rendContext->GetDrawTarget(), aMetrics, aStatus);
 
   NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aMetrics);
 }
 
 #ifdef ACCESSIBILITY
 /**
  * Notifies accessibility about text reflow. Used by nsTextFrame::ReflowText.
  */
@@ -8477,17 +8482,17 @@ private:
 
   nsIContent* mContent;
   nsPresContext* mPresContext;
 };
 #endif
 
 void
 nsTextFrame::ReflowText(nsLineLayout& aLineLayout, nscoord aAvailableWidth,
-                        nsRenderingContext* aRenderingContext,
+                        DrawTarget* aDrawTarget,
                         nsHTMLReflowMetrics& aMetrics,
                         nsReflowStatus& aStatus)
 {
 #ifdef NOISY_REFLOW
   ListTag(stdout);
   printf(": BeginReflow: availableWidth=%d\n", aAvailableWidth);
 #endif
 
@@ -8528,17 +8533,16 @@ nsTextFrame::ReflowText(nsLineLayout& aL
 
   bool atStartOfLine = aLineLayout.LineAtStart();
   if (atStartOfLine) {
     AddStateBits(TEXT_START_OF_LINE);
   }
 
   uint32_t flowEndInTextRun;
   nsIFrame* lineContainer = aLineLayout.LineContainerFrame();
-  gfxContext* ctx = aRenderingContext->ThebesContext();
   const nsTextFragment* frag = mContent->GetText();
 
   // DOM offsets of the text range we need to measure, after trimming
   // whitespace, restricting to first-letter, and restricting preformatted text
   // to nearest newline
   int32_t length = maxContentLength;
   int32_t offset = GetContentOffset();
 
@@ -8598,17 +8602,17 @@ nsTextFrame::ReflowText(nsLineLayout& aL
     if (aLineLayout.GetInFirstLetter()) {
       // floating first-letter boundaries are significant in textrun
       // construction, so clear the textrun out every time we hit a first-letter
       // and have changed our length (which controls the first-letter boundary)
       ClearTextRuns();
       // Find the length of the first-letter. We need a textrun for this.
       // REVIEW: maybe-bogus inflation should be ok (fixed below)
       gfxSkipCharsIterator iter =
-        EnsureTextRun(nsTextFrame::eInflated, ctx,
+        EnsureTextRun(nsTextFrame::eInflated, aDrawTarget,
                       lineContainer, aLineLayout.GetLine(),
                       &flowEndInTextRun);
 
       if (mTextRun) {
         int32_t firstLetterLength = length;
         if (aLineLayout.GetFirstLetterStyleOK()) {
           completedFirstLetter =
             FindFirstLetterRange(frag, mTextRun, offset, iter, &firstLetterLength);
@@ -8650,29 +8654,29 @@ nsTextFrame::ReflowText(nsLineLayout& aL
 
   if (!IsCurrentFontInflation(fontSizeInflation)) {
     // FIXME: Ideally, if we already have a text run, we'd move it to be
     // the uninflated text run.
     ClearTextRun(nullptr, nsTextFrame::eInflated);
   }
 
   gfxSkipCharsIterator iter =
-    EnsureTextRun(nsTextFrame::eInflated, ctx,
+    EnsureTextRun(nsTextFrame::eInflated, aDrawTarget,
                   lineContainer, aLineLayout.GetLine(), &flowEndInTextRun);
 
   NS_ASSERTION(IsCurrentFontInflation(fontSizeInflation),
                "EnsureTextRun should have set font size inflation");
 
   if (mTextRun && iter.GetOriginalEnd() < offset + length) {
     // The textrun does not map enough text for this frame. This can happen
     // when the textrun was ended in the middle of a text node because a
     // preformatted newline was encountered, and prev-in-flow frames have
     // consumed all the text of the textrun. We need a new textrun.
     ClearTextRuns();
-    iter = EnsureTextRun(nsTextFrame::eInflated, ctx,
+    iter = EnsureTextRun(nsTextFrame::eInflated, aDrawTarget,
                          lineContainer, aLineLayout.GetLine(),
                          &flowEndInTextRun);
   }
 
   if (!mTextRun) {
     ClearMetrics(aMetrics);
     aStatus = NS_FRAME_COMPLETE;
     return;
@@ -8746,17 +8750,18 @@ nsTextFrame::ReflowText(nsLineLayout& aL
     suppressBreak = gfxTextRun::eSuppressInitialBreak;
   }
   uint32_t transformedCharsFit =
     mTextRun->BreakAndMeasureText(transformedOffset, transformedLength,
                                   (GetStateBits() & TEXT_START_OF_LINE) != 0,
                                   availWidth,
                                   &provider, suppressBreak,
                                   canTrimTrailingWhitespace ? &trimmedWidth : nullptr,
-                                  &textMetrics, boundingBoxType, ctx,
+                                  &textMetrics, boundingBoxType,
+                                  aDrawTarget,
                                   &usedHyphenation, &transformedLastBreak,
                                   textStyle->WordCanWrap(this), &breakPriority);
   if (!length && !textMetrics.mAscent && !textMetrics.mDescent) {
     // If we're measuring a zero-length piece of text, update
     // the height manually.
     nsFontMetrics* fm = provider.GetFontMetrics();
     if (fm) {
       textMetrics.mAscent = gfxFloat(fm->MaxAscent());
@@ -8796,17 +8801,18 @@ nsTextFrame::ReflowText(nsLineLayout& aL
     // note that this is a hyphenation break.
     if ((forceBreak >= 0 || forceBreakAfter) &&
         HasSoftHyphenBefore(frag, mTextRun, offset, end)) {
       usedHyphenation = true;
     }
   }
   if (usedHyphenation) {
     // Fix up metrics to include hyphen
-    AddHyphenToMetrics(this, mTextRun, &textMetrics, boundingBoxType, ctx);
+    AddHyphenToMetrics(this, mTextRun, &textMetrics, boundingBoxType,
+                       aDrawTarget);
     AddStateBits(TEXT_HYPHEN_BREAK | TEXT_HAS_NONCOLLAPSED_CHARACTERS);
   }
   if (textMetrics.mBoundingBox.IsEmpty()) {
     AddStateBits(TEXT_NO_RENDERED_GLYPHS);
   }
 
   gfxFloat trimmableWidth = 0;
   bool brokeText = forceBreak >= 0 || transformedCharsFit < transformedLength;
@@ -9035,31 +9041,30 @@ nsTextFrame::ReflowText(nsLineLayout& aL
 /* virtual */ bool
 nsTextFrame::CanContinueTextRun() const
 {
   // We can continue a text run through a text frame
   return true;
 }
 
 nsTextFrame::TrimOutput
-nsTextFrame::TrimTrailingWhiteSpace(nsRenderingContext* aRC)
+nsTextFrame::TrimTrailingWhiteSpace(DrawTarget* aDrawTarget)
 {
   TrimOutput result;
   result.mChanged = false;
   result.mDeltaWidth = 0;
 
   AddStateBits(TEXT_END_OF_LINE);
 
   int32_t contentLength = GetContentLength();
   if (!contentLength)
     return result;
 
-  gfxContext* ctx = aRC->ThebesContext();
   gfxSkipCharsIterator start =
-    EnsureTextRun(nsTextFrame::eInflated, ctx);
+    EnsureTextRun(nsTextFrame::eInflated, aDrawTarget);
   NS_ENSURE_TRUE(mTextRun, result);
 
   uint32_t trimmedStart = start.GetSkippedOffset();
 
   const nsTextFragment* frag = mContent->GetText();
   TrimmedOffsets trimmed = GetTrimmedOffsets(frag, true);
   gfxSkipCharsIterator trimmedEndIter = start;
   const nsStyleText* textStyle = StyleText();
@@ -9078,17 +9083,17 @@ nsTextFrame::TrimTrailingWhiteSpace(nsRe
       delta = mTextRun->GetAdvanceWidth(trimmedEnd, endOffset - trimmedEnd, &provider);
       result.mChanged = true;
     }
   }
 
   gfxFloat advanceDelta;
   mTextRun->SetLineBreaks(trimmedStart, trimmedEnd - trimmedStart,
                           (GetStateBits() & TEXT_START_OF_LINE) != 0, true,
-                          &advanceDelta, ctx);
+                          &advanceDelta);
   if (advanceDelta != 0) {
     result.mChanged = true;
   }
 
   // aDeltaWidth is *subtracted* from our width.
   // If advanceDelta is positive then setting the line break made us longer,
   // so aDeltaWidth could go negative.
   result.mDeltaWidth = NSToCoordFloor(delta - advanceDelta);
--- a/layout/generic/nsTextFrame.h
+++ b/layout/generic/nsTextFrame.h
@@ -238,17 +238,17 @@ public:
   ComputeSize(nsRenderingContext *aRenderingContext,
               mozilla::WritingMode aWritingMode,
               const mozilla::LogicalSize& aCBSize,
               nscoord aAvailableISize,
               const mozilla::LogicalSize& aMargin,
               const mozilla::LogicalSize& aBorder,
               const mozilla::LogicalSize& aPadding,
               ComputeSizeFlags aFlags) override;
-  virtual nsRect ComputeTightBounds(gfxContext* aContext) const override;
+  virtual nsRect ComputeTightBounds(DrawTarget* aDrawTarget) const override;
   virtual nsresult GetPrefWidthTightBounds(nsRenderingContext* aContext,
                                            nscoord* aX,
                                            nscoord* aXMost) override;
   virtual void Reflow(nsPresContext* aPresContext,
                       nsHTMLReflowMetrics& aMetrics,
                       const nsHTMLReflowState& aReflowState,
                       nsReflowStatus& aStatus) override;
   virtual bool CanContinueTextRun() const override;
@@ -257,17 +257,17 @@ public:
   // placeholders or inlines containing such).
   struct TrimOutput {
     // true if we trimmed some space or changed metrics in some other way.
     // In this case, we should call RecomputeOverflow on this frame.
     bool mChanged;
     // an amount to *subtract* from the frame's width (zero if !mChanged)
     nscoord      mDeltaWidth;
   };
-  TrimOutput TrimTrailingWhiteSpace(nsRenderingContext* aRC);
+  TrimOutput TrimTrailingWhiteSpace(DrawTarget* aDrawTarget);
   virtual RenderedText GetRenderedText(uint32_t aStartOffset = 0,
                                        uint32_t aEndOffset = UINT32_MAX,
                                        TextOffsetType aOffsetType =
                                            TextOffsetType::OFFSETS_IN_CONTENT_TEXT,
                                        TrailingWhitespace aTrimTrailingWhitespace =
                                            TrailingWhitespace::TRIM_TRAILING_WHITESPACE) override;
 
   nsOverflowAreas RecomputeOverflow(nsIFrame* aBlockFrame);
@@ -470,29 +470,28 @@ public:
   // and going to the end of the text node or the next bidi continuation
   // boundary.
   int32_t GetInFlowContentLength();
 
   /**
    * Acquires the text run for this content, if necessary.
    * @param aWhichTextRun indicates whether to get an inflated or non-inflated
    * text run
-   * @param aReferenceContext the rendering context to use as a reference for
-   * creating the textrun, if available (if not, we'll create one which will
-   * just be slower)
+   * @param aRefDrawTarget the DrawTarget to use as a reference for creating the
+   * textrun, if available (if not, we'll create one which will just be slower)
    * @param aLineContainer the block ancestor for this frame, or nullptr if
    * unknown
    * @param aFlowEndInTextRun if non-null, this returns the textrun offset of
    * end of the text associated with this frame and its in-flow siblings
    * @return a gfxSkipCharsIterator set up to map DOM offsets for this frame
    * to offsets into the textrun; its initial offset is set to this frame's
    * content offset
    */
   gfxSkipCharsIterator EnsureTextRun(TextRunType aWhichTextRun,
-                                     gfxContext* aReferenceContext = nullptr,
+                                     DrawTarget* aRefDrawTarget = nullptr,
                                      nsIFrame* aLineContainer = nullptr,
                                      const nsLineList::iterator* aLine = nullptr,
                                      uint32_t* aFlowEndInTextRun = nullptr);
 
   gfxTextRun* GetTextRun(TextRunType aWhichTextRun) {
     if (aWhichTextRun == eInflated || !HasFontSizeInflation())
       return mTextRun;
     return GetUninflatedTextRun();
@@ -541,17 +540,17 @@ public:
     int32_t mLength;
     int32_t GetEnd() const { return mStart + mLength; }
   };
   TrimmedOffsets GetTrimmedOffsets(const nsTextFragment* aFrag,
                                    bool aTrimAfter, bool aPostReflow = true);
 
   // Similar to Reflow(), but for use from nsLineLayout
   void ReflowText(nsLineLayout& aLineLayout, nscoord aAvailableWidth,
-                  nsRenderingContext* aRenderingContext,
+                  DrawTarget* aDrawTarget,
                   nsHTMLReflowMetrics& aMetrics, nsReflowStatus& aStatus);
 
   bool IsFloatingFirstLetterChild() const;
 
   virtual bool UpdateOverflow() override;
 
   void AssignJustificationGaps(const mozilla::JustificationAssignment& aAssign);
   mozilla::JustificationAssignment GetJustificationAssignment() const;
--- a/layout/generic/nsTextRunTransformations.cpp
+++ b/layout/generic/nsTextRunTransformations.cpp
@@ -208,20 +208,20 @@ MergeCharactersInTextRun(gfxTextRun* aDe
     NS_ASSERTION(glyphs.Length() == 0,
                  "Leftover glyphs, don't request merging of the last character with its next!");  
   }
   NS_ASSERTION(offset == aDest->GetLength(), "Bad offset calculations");
 }
 
 gfxTextRunFactory::Parameters
 GetParametersForInner(nsTransformedTextRun* aTextRun, uint32_t* aFlags,
-    gfxContext* aRefContext)
+                      DrawTarget* aRefDrawTarget)
 {
   gfxTextRunFactory::Parameters params =
-    { aRefContext, nullptr, nullptr,
+    { aRefDrawTarget, nullptr, nullptr,
       nullptr, 0, aTextRun->GetAppUnitsPerDevUnit()
     };
   *aFlags = aTextRun->GetFlags() & ~gfxFontGroup::TEXT_IS_PERSISTENT;
   return params;
 }
 
 // Some languages have special casing conventions that differ from the
 // default Unicode mappings.
@@ -596,17 +596,18 @@ nsCaseTransformTextRunFactory::Transform
     }
   }
 
   return mergeNeeded;
 }
 
 void
 nsCaseTransformTextRunFactory::RebuildTextRun(nsTransformedTextRun* aTextRun,
-    gfxContext* aRefContext, gfxMissingFontRecorder *aMFR)
+                                              DrawTarget* aRefDrawTarget,
+                                              gfxMissingFontRecorder* aMFR)
 {
   nsAutoString convertedString;
   nsAutoTArray<bool,50> charsToMergeArray;
   nsAutoTArray<bool,50> deletedCharsArray;
   nsAutoTArray<uint8_t,50> canBreakBeforeArray;
   nsAutoTArray<RefPtr<nsTransformedCharStyle>,50> styleArray;
 
   bool mergeNeeded = TransformString(aTextRun->mString,
@@ -616,17 +617,17 @@ nsCaseTransformTextRunFactory::RebuildTe
                                      charsToMergeArray,
                                      deletedCharsArray,
                                      aTextRun,
                                      &canBreakBeforeArray,
                                      &styleArray);
 
   uint32_t flags;
   gfxTextRunFactory::Parameters innerParams =
-      GetParametersForInner(aTextRun, &flags, aRefContext);
+    GetParametersForInner(aTextRun, &flags, aRefDrawTarget);
   gfxFontGroup* fontGroup = aTextRun->GetFontGroup();
 
   nsAutoPtr<nsTransformedTextRun> transformedChild;
   nsAutoPtr<gfxTextRun> cachedChild;
   gfxTextRun* child;
 
   if (mInnerTransformingTextRunFactory) {
     transformedChild = mInnerTransformingTextRunFactory->MakeTextRun(
@@ -643,17 +644,17 @@ nsCaseTransformTextRunFactory::RebuildTe
     return;
   // Copy potential linebreaks into child so they're preserved
   // (and also child will be shaped appropriately)
   NS_ASSERTION(convertedString.Length() == canBreakBeforeArray.Length(),
                "Dropped characters or break-before values somewhere!");
   child->SetPotentialLineBreaks(0, canBreakBeforeArray.Length(),
                                 canBreakBeforeArray.Elements());
   if (transformedChild) {
-    transformedChild->FinishSettingProperties(aRefContext, aMFR);
+    transformedChild->FinishSettingProperties(aRefDrawTarget, aMFR);
   }
 
   if (mergeNeeded) {
     // Now merge multiple characters into one multi-glyph character as required
     // and deal with skipping deleted accent chars
     NS_ASSERTION(charsToMergeArray.Length() == child->GetLength(),
                  "source length mismatch");
     NS_ASSERTION(deletedCharsArray.Length() == aTextRun->GetLength(),
--- a/layout/generic/nsTextRunTransformations.h
+++ b/layout/generic/nsTextRunTransformations.h
@@ -51,17 +51,17 @@ public:
                                     bool aOwnsFactory);
   nsTransformedTextRun* MakeTextRun(const char16_t* aString, uint32_t aLength,
                                     const gfxFontGroup::Parameters* aParams,
                                     gfxFontGroup* aFontGroup, uint32_t aFlags,
                                     nsTArray<RefPtr<nsTransformedCharStyle>>&& aStyles,
                                     bool aOwnsFactory);
 
   virtual void RebuildTextRun(nsTransformedTextRun* aTextRun,
-                              gfxContext* aRefContext,
+                              mozilla::gfx::DrawTarget* aRefDrawTarget,
                               gfxMissingFontRecorder* aMFR) = 0;
 };
 
 /**
  * Builds textruns that transform the text in some way (e.g., capitalize)
  * and then render the text using some other textrun implementation.
  */
 class nsCaseTransformTextRunFactory : public nsTransformingTextRunFactory {
@@ -74,17 +74,17 @@ public:
   
   // Takes ownership of aInnerTransformTextRunFactory
   explicit nsCaseTransformTextRunFactory(nsTransformingTextRunFactory* aInnerTransformingTextRunFactory,
                                          bool aAllUppercase = false)
     : mInnerTransformingTextRunFactory(aInnerTransformingTextRunFactory),
       mAllUppercase(aAllUppercase) {}
 
   virtual void RebuildTextRun(nsTransformedTextRun* aTextRun,
-                              gfxContext* aRefContext,
+                              mozilla::gfx::DrawTarget* aRefDrawTarget,
                               gfxMissingFontRecorder* aMFR) override;
 
   // Perform a transformation on the given string, writing the result into
   // aConvertedString. If aAllUppercase is true, the transform is (global)
   // upper-casing, and aLanguage is used to determine any language-specific
   // behavior; otherwise, an nsTransformedTextRun should be passed in
   // as aTextRun and its styles will be used to determine the transform(s)
   // to be applied.
@@ -132,22 +132,22 @@ public:
                          bool* aCapitalization);
   virtual bool SetPotentialLineBreaks(uint32_t aStart, uint32_t aLength,
                                       uint8_t* aBreakBefore);
   /**
    * Called after SetCapitalization and SetPotentialLineBreaks
    * are done and before we request any data from the textrun. Also always
    * called after a Create.
    */
-  void FinishSettingProperties(gfxContext* aRefContext,
+  void FinishSettingProperties(mozilla::gfx::DrawTarget* aRefDrawTarget,
                                gfxMissingFontRecorder* aMFR)
   {
     if (mNeedsRebuild) {
       mNeedsRebuild = false;
-      mFactory->RebuildTextRun(this, aRefContext, aMFR);
+      mFactory->RebuildTextRun(this, aRefDrawTarget, aMFR);
     }
   }
 
   // override the gfxTextRun impls to account for additional members here
   virtual size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) MOZ_MUST_OVERRIDE;
   virtual size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) MOZ_MUST_OVERRIDE;
 
   nsTransformingTextRunFactory       *mFactory;
@@ -204,12 +204,12 @@ private:
  * position in aDest was deleted (has no corresponding char in aSrc)
  */
 void
 MergeCharactersInTextRun(gfxTextRun* aDest, gfxTextRun* aSrc,
                          const bool* aCharsToMerge, const bool* aDeletedChars);
 
 gfxTextRunFactory::Parameters
 GetParametersForInner(nsTransformedTextRun* aTextRun, uint32_t* aFlags,
-                      gfxContext* aRefContext);
+                      mozilla::gfx::DrawTarget* aRefDrawTarget);
 
 
 #endif /*NSTEXTRUNTRANSFORMATIONS_H_*/
--- a/layout/mathml/nsIMathMLFrame.h
+++ b/layout/mathml/nsIMathMLFrame.h
@@ -76,17 +76,17 @@ public:
   *        stretch.
   * @param aContainerSize [in] struct that suggests the maximumn size for
   *        the stretched frame. Only member data of the struct that are 
   *        relevant to the direction are used (the rest is ignored). 
   * @param aDesiredStretchSize [in/out] On input the current size
   *        of the frame, on output the size after stretching.
   */
   NS_IMETHOD 
-  Stretch(nsRenderingContext& aRenderingContext,
+  Stretch(mozilla::gfx::DrawTarget* aDrawTarget,
           nsStretchDirection   aStretchDirection,
           nsBoundingMetrics&   aContainerSize,
           nsHTMLReflowMetrics& aDesiredStretchSize) = 0;
 
  /* Get the mEmbellishData member variable. */
  
   NS_IMETHOD
   GetEmbellishData(nsEmbellishData& aEmbellishData) = 0;
--- a/layout/mathml/nsMathMLChar.cpp
+++ b/layout/mathml/nsMathMLChar.cpp
@@ -82,37 +82,37 @@ static const nsGlyphCode kNullGlyph = {{
 class nsGlyphTable {
 public:
   virtual ~nsGlyphTable() {}
 
   virtual const FontFamilyName&
   FontNameFor(const nsGlyphCode& aGlyphCode) const = 0;
 
   // Getters for the parts
-  virtual nsGlyphCode ElementAt(gfxContext*   aThebesContext,
+  virtual nsGlyphCode ElementAt(DrawTarget*   aDrawTarget,
                                 int32_t       aAppUnitsPerDevPixel,
                                 gfxFontGroup* aFontGroup,
                                 char16_t      aChar,
                                 bool          aVertical,
                                 uint32_t      aPosition) = 0;
-  virtual nsGlyphCode BigOf(gfxContext*   aThebesContext,
+  virtual nsGlyphCode BigOf(DrawTarget*   aDrawTarget,
                             int32_t       aAppUnitsPerDevPixel,
                             gfxFontGroup* aFontGroup,
                             char16_t      aChar,
                             bool          aVertical,
                             uint32_t      aSize) = 0;
 
   // True if this table contains parts to render this char
-  virtual bool HasPartsOf(gfxContext*   aThebesContext,
+  virtual bool HasPartsOf(DrawTarget*   aDrawTarget,
                           int32_t       aAppUnitsPerDevPixel,
                           gfxFontGroup* aFontGroup,
                           char16_t      aChar,
                           bool          aVertical) = 0;
 
-  virtual gfxTextRun* MakeTextRun(gfxContext*        aThebesContext,
+  virtual gfxTextRun* MakeTextRun(DrawTarget*        aDrawTarget,
                                   int32_t            aAppUnitsPerDevPixel,
                                   gfxFontGroup*      aFontGroup,
                                   const nsGlyphCode& aGlyph) = 0;
 protected:
   nsGlyphTable() : mCharCache(0) {}
   // For speedy re-use, we always cache the last data used in the table.
   // mCharCache is the Unicode point of the last char that was queried in this
   // table.
@@ -189,51 +189,51 @@ public:
   const FontFamilyName&
   FontNameFor(const nsGlyphCode& aGlyphCode) const override
   {
     NS_ASSERTION(!aGlyphCode.IsGlyphID(),
                  "nsPropertiesTable can only access glyphs by code point");
     return mGlyphCodeFonts[aGlyphCode.font];
   }
 
-  virtual nsGlyphCode ElementAt(gfxContext*   aThebesContext,
+  virtual nsGlyphCode ElementAt(DrawTarget*   aDrawTarget,
                                 int32_t       aAppUnitsPerDevPixel,
                                 gfxFontGroup* aFontGroup,
                                 char16_t      aChar,
                                 bool          aVertical,
                                 uint32_t      aPosition) override;
 
-  virtual nsGlyphCode BigOf(gfxContext*   aThebesContext,
+  virtual nsGlyphCode BigOf(DrawTarget*   aDrawTarget,
                             int32_t       aAppUnitsPerDevPixel,
                             gfxFontGroup* aFontGroup,
                             char16_t      aChar,
                             bool          aVertical,
                             uint32_t      aSize) override
   {
-    return ElementAt(aThebesContext, aAppUnitsPerDevPixel, aFontGroup,
+    return ElementAt(aDrawTarget, aAppUnitsPerDevPixel, aFontGroup,
                      aChar, aVertical, 4 + aSize);
   }
 
-  virtual bool HasPartsOf(gfxContext*   aThebesContext,
+  virtual bool HasPartsOf(DrawTarget*   aDrawTarget,
                           int32_t       aAppUnitsPerDevPixel,
                           gfxFontGroup* aFontGroup,
                           char16_t      aChar,
                           bool          aVertical) override
   {
-    return (ElementAt(aThebesContext, aAppUnitsPerDevPixel, aFontGroup,
+    return (ElementAt(aDrawTarget, aAppUnitsPerDevPixel, aFontGroup,
                       aChar, aVertical, 0).Exists() ||
-            ElementAt(aThebesContext, aAppUnitsPerDevPixel, aFontGroup,
+            ElementAt(aDrawTarget, aAppUnitsPerDevPixel, aFontGroup,
                       aChar, aVertical, 1).Exists() ||
-            ElementAt(aThebesContext, aAppUnitsPerDevPixel, aFontGroup,
+            ElementAt(aDrawTarget, aAppUnitsPerDevPixel, aFontGroup,
                       aChar, aVertical, 2).Exists() ||
-            ElementAt(aThebesContext, aAppUnitsPerDevPixel, aFontGroup,
+            ElementAt(aDrawTarget, aAppUnitsPerDevPixel, aFontGroup,
                       aChar, aVertical, 3).Exists());
   }
 
-  virtual gfxTextRun* MakeTextRun(gfxContext*        aThebesContext,
+  virtual gfxTextRun* MakeTextRun(DrawTarget*        aDrawTarget,
                                   int32_t            aAppUnitsPerDevPixel,
                                   gfxFontGroup*      aFontGroup,
                                   const nsGlyphCode& aGlyph) override;
 private:
 
   // mGlyphCodeFonts[0] is the primary font associated to this table. The
   // others are possible "external" fonts for glyphs not in the primary font
   // but which are needed to stretch certain characters in the table
@@ -263,17 +263,17 @@ private:
   // A font identifier of '0' means the default primary font associated to this
   // table. Other digits map to the "external" fonts that may have been
   // specified in the MathFont Property File.
   nsString  mGlyphCache;
 };
 
 /* virtual */
 nsGlyphCode
-nsPropertiesTable::ElementAt(gfxContext*   /* aThebesContext */,
+nsPropertiesTable::ElementAt(DrawTarget*   /* aDrawTarget */,
                              int32_t       /* aAppUnitsPerDevPixel */,
                              gfxFontGroup* /* aFontGroup */,
                              char16_t      aChar,
                              bool          /* aVertical */,
                              uint32_t      aPosition)
 {
   if (mState == NS_TABLE_STATE_ERROR) return kNullGlyph;
   // Load glyph properties if this is the first time we have been here
@@ -376,65 +376,65 @@ nsPropertiesTable::ElementAt(gfxContext*
   ch.code[0] = mGlyphCache.CharAt(index);
   ch.code[1] = mGlyphCache.CharAt(index + 1);
   ch.font = mGlyphCache.CharAt(index + 2);
   return ch.code[0] == char16_t(0xFFFD) ? kNullGlyph : ch;
 }
 
 /* virtual */
 gfxTextRun*
-nsPropertiesTable::MakeTextRun(gfxContext*        aThebesContext,
+nsPropertiesTable::MakeTextRun(DrawTarget*        aDrawTarget,
                                int32_t            aAppUnitsPerDevPixel,
                                gfxFontGroup*      aFontGroup,
                                const nsGlyphCode& aGlyph)
 {
   NS_ASSERTION(!aGlyph.IsGlyphID(),
                "nsPropertiesTable can only access glyphs by code point");
   return aFontGroup->
-    MakeTextRun(aGlyph.code, aGlyph.Length(), aThebesContext,
+    MakeTextRun(aGlyph.code, aGlyph.Length(), aDrawTarget,
                 aAppUnitsPerDevPixel, 0, nullptr);
 }
 
 // An instance of nsOpenTypeTable is associated with one gfxFontEntry that
 // corresponds to an Open Type font with a MATH table. All the glyphs come from
 // the same font and the calls to access size variants and parts are directly
 // forwarded to the gfx code.
 class nsOpenTypeTable final : public nsGlyphTable {
 public:
   ~nsOpenTypeTable()
   {
     MOZ_COUNT_DTOR(nsOpenTypeTable);
   }
 
-  virtual nsGlyphCode ElementAt(gfxContext*   aThebesContext,
+  virtual nsGlyphCode ElementAt(DrawTarget*   aDrawTarget,
                                 int32_t       aAppUnitsPerDevPixel,
                                 gfxFontGroup* aFontGroup,
                                 char16_t      aChar,
                                 bool          aVertical,
                                 uint32_t      aPosition) override;
-  virtual nsGlyphCode BigOf(gfxContext*   aThebesContext,
+  virtual nsGlyphCode BigOf(DrawTarget*   aDrawTarget,
                             int32_t       aAppUnitsPerDevPixel,
                             gfxFontGroup* aFontGroup,
                             char16_t      aChar,
                             bool          aVertical,
                             uint32_t      aSize) override;
-  virtual bool HasPartsOf(gfxContext*   aThebesContext,
+  virtual bool HasPartsOf(DrawTarget*   aDrawTarget,
                           int32_t       aAppUnitsPerDevPixel,
                           gfxFontGroup* aFontGroup,
                           char16_t      aChar,
                           bool          aVertical) override;
 
   const FontFamilyName&
   FontNameFor(const nsGlyphCode& aGlyphCode) const override {
     NS_ASSERTION(aGlyphCode.IsGlyphID(),
                  "nsOpenTypeTable can only access glyphs by id");
     return mFontFamilyName;
   }
 
-  virtual gfxTextRun* MakeTextRun(gfxContext*        aThebesContext,
+  virtual gfxTextRun* MakeTextRun(DrawTarget*        aDrawTarget,
                                   int32_t            aAppUnitsPerDevPixel,
                                   gfxFontGroup*      aFontGroup,
                                   const nsGlyphCode& aGlyph) override;
 
   // This returns a new OpenTypeTable instance to give access to OpenType MATH
   // table or nullptr if the font does not have such table. Ownership is passed
   // to the caller.
   static nsOpenTypeTable* Create(gfxFont* aFont)
@@ -451,54 +451,54 @@ private:
   uint32_t mGlyphID;
 
   explicit nsOpenTypeTable(gfxFontEntry* aFontEntry)
     : mFontEntry(aFontEntry),
       mFontFamilyName(aFontEntry->FamilyName(), eUnquotedName) {
     MOZ_COUNT_CTOR(nsOpenTypeTable);
   }
 
-  void UpdateCache(gfxContext*   aThebesContext,
+  void UpdateCache(DrawTarget*   aDrawTarget,
                    int32_t       aAppUnitsPerDevPixel,
                    gfxFontGroup* aFontGroup,
                    char16_t      aChar);
 };
 
 void
-nsOpenTypeTable::UpdateCache(gfxContext*   aThebesContext,
+nsOpenTypeTable::UpdateCache(DrawTarget*   aDrawTarget,
                              int32_t       aAppUnitsPerDevPixel,
                              gfxFontGroup* aFontGroup,
                              char16_t      aChar)
 {
   if (mCharCache != aChar) {
     nsAutoPtr<gfxTextRun> textRun;
     textRun = aFontGroup->
-      MakeTextRun(&aChar, 1, aThebesContext, aAppUnitsPerDevPixel, 0, nullptr);
+      MakeTextRun(&aChar, 1, aDrawTarget, aAppUnitsPerDevPixel, 0, nullptr);
     const gfxTextRun::CompressedGlyph& data = textRun->GetCharacterGlyphs()[0];
     if (data.IsSimpleGlyph()) {
       mGlyphID = data.GetSimpleGlyph();
     } else if (data.GetGlyphCount() == 1) {
       mGlyphID = textRun->GetDetailedGlyphs(0)->mGlyphID;
     } else {
       mGlyphID = 0;
     }
     mCharCache = aChar;
   }
 }
 
 /* virtual */
 nsGlyphCode
-nsOpenTypeTable::ElementAt(gfxContext*   aThebesContext,
+nsOpenTypeTable::ElementAt(DrawTarget*   aDrawTarget,
                            int32_t       aAppUnitsPerDevPixel,
                            gfxFontGroup* aFontGroup,
                            char16_t      aChar,
                            bool          aVertical,
                            uint32_t      aPosition)
 {
-  UpdateCache(aThebesContext, aAppUnitsPerDevPixel, aFontGroup, aChar);
+  UpdateCache(aDrawTarget, aAppUnitsPerDevPixel, aFontGroup, aChar);
 
   uint32_t parts[4];
   if (!mFontEntry->GetMathVariantsParts(mGlyphID, aVertical, parts)) {
     return kNullGlyph;
   }
 
   uint32_t glyphID = parts[aPosition];
   if (!glyphID) {
@@ -507,80 +507,80 @@ nsOpenTypeTable::ElementAt(gfxContext*  
   nsGlyphCode glyph;
   glyph.glyphID = glyphID;
   glyph.font = -1;
   return glyph;
 }
 
 /* virtual */
 nsGlyphCode
-nsOpenTypeTable::BigOf(gfxContext*   aThebesContext,
+nsOpenTypeTable::BigOf(DrawTarget*   aDrawTarget,
                        int32_t       aAppUnitsPerDevPixel,
                        gfxFontGroup* aFontGroup,
                        char16_t      aChar,
                        bool          aVertical,
                        uint32_t      aSize)
 {
-  UpdateCache(aThebesContext, aAppUnitsPerDevPixel, aFontGroup, aChar);
+  UpdateCache(aDrawTarget, aAppUnitsPerDevPixel, aFontGroup, aChar);
 
   uint32_t glyphID =
     mFontEntry->GetMathVariantsSize(mGlyphID, aVertical, aSize);
   if (!glyphID) {
     return kNullGlyph;
   }
 
   nsGlyphCode glyph;
   glyph.glyphID = glyphID;
   glyph.font = -1;
   return glyph;
 }
 
 /* virtual */
 bool
-nsOpenTypeTable::HasPartsOf(gfxContext*   aThebesContext,
+nsOpenTypeTable::HasPartsOf(DrawTarget*   aDrawTarget,
                             int32_t       aAppUnitsPerDevPixel,
                             gfxFontGroup* aFontGroup,
                             char16_t      aChar,
                             bool          aVertical)
 {
-  UpdateCache(aThebesContext, aAppUnitsPerDevPixel, aFontGroup, aChar);
+  UpdateCache(aDrawTarget, aAppUnitsPerDevPixel, aFontGroup, aChar);
 
   uint32_t parts[4];
   if (!mFontEntry->GetMathVariantsParts(mGlyphID, aVertical, parts)) {
     return false;
   }
 
   return parts[0] || parts[1] || parts[2] || parts[3];
 }
 
 /* virtual */
 gfxTextRun*
-nsOpenTypeTable::MakeTextRun(gfxContext*        aThebesContext,
+nsOpenTypeTable::MakeTextRun(DrawTarget*        aDrawTarget,
                              int32_t            aAppUnitsPerDevPixel,
                              gfxFontGroup*      aFontGroup,
                              const nsGlyphCode& aGlyph)
 {
   NS_ASSERTION(aGlyph.IsGlyphID(),
                "nsOpenTypeTable can only access glyphs by id");
 
   gfxTextRunFactory::Parameters params = {
-    aThebesContext, nullptr, nullptr, nullptr, 0, aAppUnitsPerDevPixel
+    aDrawTarget, nullptr, nullptr, nullptr, 0, aAppUnitsPerDevPixel
   };
   gfxTextRun* textRun = gfxTextRun::Create(&params, 1, aFontGroup, 0);
   textRun->AddGlyphRun(aFontGroup->GetFirstValidFont(),
                        gfxTextRange::kFontGroup, 0,
                        false, gfxTextRunFactory::TEXT_ORIENT_HORIZONTAL);
                               // We don't care about CSS writing mode here;
                               // math runs are assumed to be horizontal.
   gfxTextRun::DetailedGlyph detailedGlyph;
   detailedGlyph.mGlyphID = aGlyph.glyphID;
   detailedGlyph.mAdvance =
     NSToCoordRound(aAppUnitsPerDevPixel *
                    aFontGroup->GetFirstValidFont()->
-                   GetGlyphHAdvance(aThebesContext, aGlyph.glyphID));
+                   GetGlyphHAdvance(aDrawTarget, aGlyph.glyphID));
   detailedGlyph.mXOffset = detailedGlyph.mYOffset = 0;
   gfxShapedText::CompressedGlyph g;
   g.SetComplex(true, true, 1);
   textRun->SetGlyphs(0, g, &detailedGlyph);
 
   return textRun;
 }
 
@@ -1015,48 +1015,48 @@ nsMathMLChar::SetFontFamily(nsPresContex
     } else {
       return false; // We did not set the font
     }
   }
   return true;
 }
 
 static nsBoundingMetrics
-MeasureTextRun(gfxContext* aThebesContext, gfxTextRun* aTextRun)
+MeasureTextRun(DrawTarget* aDrawTarget, gfxTextRun* aTextRun)
 {
   gfxTextRun::Metrics metrics =
     aTextRun->MeasureText(0, aTextRun->GetLength(),
                           gfxFont::TIGHT_HINTED_OUTLINE_EXTENTS,
-                          aThebesContext, nullptr);
+                          aDrawTarget, nullptr);
 
   nsBoundingMetrics bm;
   bm.leftBearing = NSToCoordFloor(metrics.mBoundingBox.X());
   bm.rightBearing = NSToCoordCeil(metrics.mBoundingBox.XMost());
   bm.ascent = NSToCoordCeil(-metrics.mBoundingBox.Y());
   bm.descent = NSToCoordCeil(metrics.mBoundingBox.YMost());
   bm.width = NSToCoordRound(metrics.mAdvanceWidth);
 
   return bm;
 }
 
 class nsMathMLChar::StretchEnumContext {
 public:
   StretchEnumContext(nsMathMLChar*        aChar,
                      nsPresContext*       aPresContext,
-                     gfxContext*          aThebesContext,
+                     DrawTarget*          aDrawTarget,
                      float                aFontSizeInflation,
                      nsStretchDirection   aStretchDirection,
                      nscoord              aTargetSize,
                      uint32_t             aStretchHint,
                      nsBoundingMetrics&   aStretchedMetrics,
                      const FontFamilyList&  aFamilyList,
                      bool&              aGlyphFound)
     : mChar(aChar),
       mPresContext(aPresContext),
-      mThebesContext(aThebesContext),
+      mDrawTarget(aDrawTarget),
       mFontSizeInflation(aFontSizeInflation),
       mDirection(aStretchDirection),
       mTargetSize(aTargetSize),
       mStretchHint(aStretchHint),
       mBoundingMetrics(aStretchedMetrics),
       mFamilyList(aFamilyList),
       mTryVariants(true),
       mTryParts(true),
@@ -1070,17 +1070,17 @@ private:
                    RefPtr<gfxFontGroup>* aFontGroup,
                    const FontFamilyList& aFamilyList);
   bool TryParts(nsGlyphTable* aGlyphTable,
                 RefPtr<gfxFontGroup>* aFontGroup,
                 const FontFamilyList& aFamilyList);
 
   nsMathMLChar* mChar;
   nsPresContext* mPresContext;
-  gfxContext* mThebesContext;
+  DrawTarget* mDrawTarget;
   float mFontSizeInflation;
   const nsStretchDirection mDirection;
   const nscoord mTargetSize;
   const uint32_t mStretchHint;
   nsBoundingMetrics& mBoundingMetrics;
   // Font families to search
   const FontFamilyList& mFamilyList;
 
@@ -1122,62 +1122,62 @@ StretchEnumContext::TryVariants(nsGlyphT
   bool haveBetter = false;
 
   // start at size = 1 (size = 0 is the char at its normal size)
   int32_t size = 1;
   nsGlyphCode ch;
   nscoord displayOperatorMinHeight = 0;
   if (largeopOnly) {
     NS_ASSERTION(isVertical, "Stretching should be in the vertical direction");
-    ch = aGlyphTable->BigOf(mThebesContext, oneDevPixel, *aFontGroup, uchar,
+    ch = aGlyphTable->BigOf(mDrawTarget, oneDevPixel, *aFontGroup, uchar,
                             isVertical, 0);
     if (ch.IsGlyphID()) {
       gfxFont* mathFont = aFontGroup->get()->GetFirstMathFont();
       // For OpenType MATH fonts, we will rely on the DisplayOperatorMinHeight
       // to select the right size variant. Note that the value is sometimes too
       // small so we use kLargeOpFactor/kIntegralFactor as a minimum value.
       if (mathFont) {
         displayOperatorMinHeight =
           mathFont->GetMathConstant(gfxFontEntry::DisplayOperatorMinHeight,
                                     oneDevPixel);
         nsAutoPtr<gfxTextRun> textRun;
-        textRun = aGlyphTable->MakeTextRun(mThebesContext, oneDevPixel,
+        textRun = aGlyphTable->MakeTextRun(mDrawTarget, oneDevPixel,
                                            *aFontGroup, ch);
-        nsBoundingMetrics bm = MeasureTextRun(mThebesContext, textRun);
+        nsBoundingMetrics bm = MeasureTextRun(mDrawTarget, textRun);
         float largeopFactor = kLargeOpFactor;
         if (NS_STRETCH_INTEGRAL & mStretchHint) {
           // integrals are drawn taller
           largeopFactor = kIntegralFactor;
         }
         nscoord minHeight = largeopFactor * (bm.ascent + bm.descent);
         if (displayOperatorMinHeight < minHeight) {
           displayOperatorMinHeight = minHeight;
         }
       }
     }
   }
 #ifdef NOISY_SEARCH
   printf("  searching in %s ...\n",
            NS_LossyConvertUTF16toASCII(aFamily).get());
 #endif
-  while ((ch = aGlyphTable->BigOf(mThebesContext, oneDevPixel, *aFontGroup,
+  while ((ch = aGlyphTable->BigOf(mDrawTarget, oneDevPixel, *aFontGroup,
                                   uchar, isVertical, size)).Exists()) {
 
     if (!mChar->SetFontFamily(mPresContext, aGlyphTable, ch, aFamilyList, font,
                               aFontGroup)) {
       // if largeopOnly is set, break now
       if (largeopOnly) break;
       ++size;
       continue;
     }
 
     nsAutoPtr<gfxTextRun> textRun;
-    textRun = aGlyphTable->MakeTextRun(mThebesContext, oneDevPixel,
+    textRun = aGlyphTable->MakeTextRun(mDrawTarget, oneDevPixel,
                                        *aFontGroup, ch);
-    nsBoundingMetrics bm = MeasureTextRun(mThebesContext, textRun);
+    nsBoundingMetrics bm = MeasureTextRun(mDrawTarget, textRun);
     if (ch.IsGlyphID()) {
       gfxFont* mathFont = aFontGroup->get()->GetFirstMathFont();
       if (mathFont) {
         // MeasureTextRun should have set the advance width to the right
         // bearing for OpenType MATH fonts. We now subtract the italic
         // correction, so that nsMathMLmmultiscripts will place the scripts
         // correctly.
         // Note that STIX-Word does not provide italic corrections but its
@@ -1262,32 +1262,32 @@ nsMathMLChar::StretchEnumContext::TryPar
   nsGlyphCode chdata[4];
   nsBoundingMetrics bmdata[4];
   nscoord sizedata[4];
 
   bool isVertical = (mDirection == NS_STRETCH_DIRECTION_VERTICAL);
   nscoord oneDevPixel = mPresContext->AppUnitsPerDevPixel();
   char16_t uchar = mChar->mData[0];
   bool maxWidth = (NS_STRETCH_MAXWIDTH & mStretchHint) != 0;
-  if (!aGlyphTable->HasPartsOf(mThebesContext, oneDevPixel, *aFontGroup,
+  if (!aGlyphTable->HasPartsOf(mDrawTarget, oneDevPixel, *aFontGroup,
                                uchar, isVertical))
     return false; // to next table
 
   for (int32_t i = 0; i < 4; i++) {
-    nsGlyphCode ch = aGlyphTable->ElementAt(mThebesContext, oneDevPixel,
+    nsGlyphCode ch = aGlyphTable->ElementAt(mDrawTarget, oneDevPixel,
                                             *aFontGroup, uchar, isVertical, i);
     chdata[i] = ch;
     if (ch.Exists()) {
       if (!mChar->SetFontFamily(mPresContext, aGlyphTable, ch, aFamilyList, font,
                                 aFontGroup))
         return false;
 
-      textRun[i] = aGlyphTable->MakeTextRun(mThebesContext, oneDevPixel,
+      textRun[i] = aGlyphTable->MakeTextRun(mDrawTarget, oneDevPixel,
                                             *aFontGroup, ch);
-      nsBoundingMetrics bm = MeasureTextRun(mThebesContext, textRun[i]);
+      nsBoundingMetrics bm = MeasureTextRun(mDrawTarget, textRun[i]);
       bmdata[i] = bm;
       sizedata[i] = isVertical ? bm.ascent + bm.descent
                                : bm.rightBearing - bm.leftBearing;
     } else {
       // Null glue indicates that a rule will be drawn, which can stretch to
       // fill any space.
       textRun[i] = nullptr;
       bmdata[i] = nsBoundingMetrics();
@@ -1509,17 +1509,17 @@ InsertMathFallbacks(FontFamilyList& aFam
   if (!inserted) {
     aMergedList.Append(aFallbacks);
   }
   aFamilyList = aMergedList;
 }
 
 nsresult
 nsMathMLChar::StretchInternal(nsPresContext*           aPresContext,
-                              gfxContext*              aThebesContext,
+                              DrawTarget*              aDrawTarget,
                               float                    aFontSizeInflation,
                               nsStretchDirection&      aStretchDirection,
                               const nsBoundingMetrics& aContainerSize,
                               nsBoundingMetrics&       aDesiredStretchSize,
                               uint32_t                 aStretchHint,
                               // These are currently only used when
                               // aStretchHint & NS_STRETCH_MAXWIDTH:
                               float                    aMaxSize,
@@ -1544,20 +1544,20 @@ nsMathMLChar::StretchInternal(nsPresCont
                   styleFont->mExplicitLanguage,
                   gfxFont::eHorizontal,
                   aPresContext->GetUserFontSet(),
                   aPresContext->GetTextPerfMetrics(),
                   *getter_AddRefs(fm));
   uint32_t len = uint32_t(mData.Length());
   nsAutoPtr<gfxTextRun> textRun;
   textRun = fm->GetThebesFontGroup()->
-    MakeTextRun(static_cast<const char16_t*>(mData.get()), len, aThebesContext,
+    MakeTextRun(static_cast<const char16_t*>(mData.get()), len, aDrawTarget,
                 aPresContext->AppUnitsPerDevPixel(), 0,
                 aPresContext->MissingFontRecorder());
-  aDesiredStretchSize = MeasureTextRun(aThebesContext, textRun);
+  aDesiredStretchSize = MeasureTextRun(aDrawTarget, textRun);
   mGlyphs[0] = textRun;
 
   bool maxWidth = (NS_STRETCH_MAXWIDTH & aStretchHint) != 0;
   if (!maxWidth) {
     mUnscaledAscent = aDesiredStretchSize.ascent;
   }
 
   //////////////////////////////////////////////////////////////////////////////
@@ -1663,17 +1663,17 @@ nsMathMLChar::StretchInternal(nsPresCont
 
 
 #ifdef NOISY_SEARCH
     nsAutoString fontlistStr;
     font.fontlist.ToString(fontlistStr, false, true);
     printf("Searching in "%s" for a glyph of appropriate size for: 0x%04X:%c\n",
            NS_ConvertUTF16toUTF8(fontlistStr).get(), mData[0], mData[0]&0x00FF);
 #endif
-    StretchEnumContext enumData(this, aPresContext, aThebesContext,
+    StretchEnumContext enumData(this, aPresContext, aDrawTarget,
                                 aFontSizeInflation,
                                 aStretchDirection, targetSize, aStretchHint,
                                 aDesiredStretchSize, font.fontlist, glyphFound);
     enumData.mTryParts = !largeopOnly;
 
     const nsTArray<FontFamilyName>& fontlist = font.fontlist.GetFontlist();
     uint32_t i, num = fontlist.Length();
     bool next = true;
@@ -1776,17 +1776,17 @@ nsMathMLChar::StretchInternal(nsPresCont
     }
   }
 
   return NS_OK;
 }
 
 nsresult
 nsMathMLChar::Stretch(nsPresContext*           aPresContext,
-                      nsRenderingContext&     aRenderingContext,
+                      DrawTarget*              aDrawTarget,
                       float                    aFontSizeInflation,
                       nsStretchDirection       aStretchDirection,
                       const nsBoundingMetrics& aContainerSize,
                       nsBoundingMetrics&       aDesiredStretchSize,
                       uint32_t                 aStretchHint,
                       bool                     aRTL)
 {
   NS_ASSERTION(!(aStretchHint &
@@ -1794,18 +1794,17 @@ nsMathMLChar::Stretch(nsPresContext*    
                    NS_STRETCH_INTEGRAL)),
                "Unexpected stretch flags");
 
   mDraw = DRAW_NORMAL;
   mMirrored = aRTL && nsMathMLOperators::IsMirrorableOperator(mData);
   mScaleY = mScaleX = 1.0;
   mDirection = aStretchDirection;
   nsresult rv =
-    StretchInternal(aPresContext, aRenderingContext.ThebesContext(),
-                    aFontSizeInflation, mDirection,
+    StretchInternal(aPresContext, aDrawTarget, aFontSizeInflation, mDirection,
                     aContainerSize, aDesiredStretchSize, aStretchHint);
 
   // Record the metrics
   mBoundingMetrics = aDesiredStretchSize;
 
   return rv;
 }
 
@@ -1817,27 +1816,24 @@ nsMathMLChar::Stretch(nsPresContext*    
 // In order to avoid considering widths of some characters in fonts that will
 // not be used for any stretch size, StretchInternal sets the initial height
 // to infinity and looks for any characters smaller than this height.  When a
 // character built from parts is considered, (it will be used by Stretch for
 // any characters greater than its minimum size, so) the height is set to its
 // minimum size, so that only widths of smaller subsequent characters are
 // considered.
 nscoord
-nsMathMLChar::GetMaxWidth(nsPresContext* aPresContext,
-                          nsRenderingContext& aRenderingContext,
-                          float aFontSizeInflation,
-                          uint32_t aStretchHint)
+nsMathMLChar::GetMaxWidth(nsPresContext* aPresContext, DrawTarget* aDrawTarget,
+                          float aFontSizeInflation, uint32_t aStretchHint)
 {
   nsBoundingMetrics bm;
   nsStretchDirection direction = NS_STRETCH_DIRECTION_VERTICAL;
   const nsBoundingMetrics container; // zero target size
 
-  StretchInternal(aPresContext, aRenderingContext.ThebesContext(),
-                  aFontSizeInflation, direction,
+  StretchInternal(aPresContext, aDrawTarget, aFontSizeInflation, direction,
                   container, bm, aStretchHint | NS_STRETCH_MAXWIDTH);
 
   return std::max(bm.width, bm.rightBearing) - std::min(0, bm.leftBearing);
 }
 
 class nsDisplayMathMLSelectionRect : public nsDisplayItem {
 public:
   nsDisplayMathMLSelectionRect(nsDisplayListBuilder* aBuilder,
--- a/layout/mathml/nsMathMLChar.h
+++ b/layout/mathml/nsMathMLChar.h
@@ -80,16 +80,18 @@ struct nsGlyphCode {
   }
 };
 
 // Class used to handle stretchy symbols (accent, delimiter and boundary
 // symbols).
 class nsMathMLChar
 {
 public:
+  typedef mozilla::gfx::DrawTarget DrawTarget;
+
   // constructor and destructor
   nsMathMLChar() {
     MOZ_COUNT_CTOR(nsMathMLChar);
     mStyleContext = nullptr;
     mUnscaledAscent = 0;
     mScaleX = mScaleY = 1.0;
     mDraw = DRAW_NORMAL;
     mMirrored = false;
@@ -109,17 +111,17 @@ public:
                        nsPoint aPt,
                        bool aIsSelected);
 
   // This is the method called to ask the char to stretch itself.
   // @param aContainerSize - IN - suggested size for the stretched char
   // @param aDesiredStretchSize - OUT - the size that the char wants
   nsresult
   Stretch(nsPresContext*           aPresContext,
-          nsRenderingContext&     aRenderingContext,
+          DrawTarget*              aDrawTarget,
           float                    aFontSizeInflation,
           nsStretchDirection       aStretchDirection,
           const nsBoundingMetrics& aContainerSize,
           nsBoundingMetrics&       aDesiredStretchSize,
           uint32_t                 aStretchHint,
           bool                     aRTL);
 
   void
@@ -159,17 +161,17 @@ public:
 
   // Get the maximum width that the character might have after a vertical
   // Stretch().
   //
   // @param aStretchHint can be the value that will be passed to Stretch().
   // It is used to determine whether the operator is stretchy or a largeop.
   nscoord
   GetMaxWidth(nsPresContext* aPresContext,
-              nsRenderingContext& aRenderingContext,
+              DrawTarget* aDrawTarget,
               float aFontSizeInflation,
               uint32_t aStretchHint = NS_STRETCH_NORMAL);
 
   // Metrics that _exactly_ enclose the char. The char *must* have *already*
   // being stretched before you can call the GetBoundingMetrics() method.
   // IMPORTANT: since chars have their own style contexts, and may be rendered
   // with glyphs that are not in the parent font, just calling the default
   // aRenderingContext.GetBoundingMetrics(aChar) can give incorrect results.
@@ -233,17 +235,17 @@ private:
                 const nsGlyphTable*     aGlyphTable,
                 const nsGlyphCode&      aGlyphCode,
                 const mozilla::FontFamilyList& aDefaultFamily,
                 nsFont&                 aFont,
                 RefPtr<gfxFontGroup>* aFontGroup);
 
   nsresult
   StretchInternal(nsPresContext*           aPresContext,
-                  gfxContext*              aThebesContext,
+                  DrawTarget*              aDrawTarget,
                   float                    aFontSizeInflation,
                   nsStretchDirection&      aStretchDirection,
                   const nsBoundingMetrics& aContainerSize,
                   nsBoundingMetrics&       aDesiredStretchSize,
                   uint32_t                 aStretchHint,
                   float           aMaxSize = NS_MATHML_OPERATOR_SIZE_INFINITY,
                   bool            aMaxSizeIsAbsolute = false);
 
--- a/layout/mathml/nsMathMLContainerFrame.cpp
+++ b/layout/mathml/nsMathMLContainerFrame.cpp
@@ -35,17 +35,17 @@ NS_QUERYFRAME_HEAD(nsMathMLContainerFram
   NS_QUERYFRAME_ENTRY(nsMathMLContainerFrame)
 NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)
 
 // =============================================================================
 
 // error handlers
 // provide a feedback to the user when a frame with bad markup can not be rendered
 nsresult
-nsMathMLContainerFrame::ReflowError(nsRenderingContext& aRenderingContext,
+nsMathMLContainerFrame::ReflowError(DrawTarget* aDrawTarget,
                                     nsHTMLReflowMetrics& aDesiredSize)
 {
   // clear all other flags and record that there is an error with this frame
   mEmbellishData.flags = 0;
   mPresentationData.flags = NS_MATHML_ERROR;
 
   ///////////////
   // Set font
@@ -53,17 +53,17 @@ nsMathMLContainerFrame::ReflowError(nsRe
   nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
                                         nsLayoutUtils::
                                         FontSizeInflationFor(this));
 
   // bounding metrics
   nsAutoString errorMsg; errorMsg.AssignLiteral("invalid-markup");
   mBoundingMetrics =
     nsLayoutUtils::AppUnitBoundsOfString(errorMsg.get(), errorMsg.Length(),
-                                         *fm, aRenderingContext);
+                                         *fm, aDrawTarget);
 
   // reflow metrics
   WritingMode wm = aDesiredSize.GetWritingMode();
   aDesiredSize.SetBlockStartAscent(fm->MaxAscent());
   nscoord descent = fm->MaxDescent();
   aDesiredSize.BSize(wm) = aDesiredSize.BlockStartAscent() + descent;
   aDesiredSize.ISize(wm) = mBoundingMetrics.width;
 
@@ -183,29 +183,29 @@ nsMathMLContainerFrame::ClearSavedChildM
     props->Delete(childFrame, HTMLReflowMetricsProperty());
     childFrame = childFrame->GetNextSibling();
   }
 }
 
 // helper to get the preferred size that a container frame should use to fire
 // the stretch on its stretchy child frames.
 void
-nsMathMLContainerFrame::GetPreferredStretchSize(nsRenderingContext& aRenderingContext,
+nsMathMLContainerFrame::GetPreferredStretchSize(DrawTarget*          aDrawTarget,
                                                 uint32_t             aOptions,
                                                 nsStretchDirection   aStretchDirection,
                                                 nsBoundingMetrics&   aPreferredStretchSize)
 {
   if (aOptions & STRETCH_CONSIDER_ACTUAL_SIZE) {
     // when our actual size is ok, just use it
     aPreferredStretchSize = mBoundingMetrics;
   }
   else if (aOptions & STRETCH_CONSIDER_EMBELLISHMENTS) {
     // compute our up-to-date size using Place()
     nsHTMLReflowMetrics metrics(GetWritingMode()); // ???
-    Place(aRenderingContext, false, metrics);
+    Place(aDrawTarget, false, metrics);
     aPreferredStretchSize = metrics.mBoundingMetrics;
   }
   else {
     // compute a size that includes embellishments iff the container stretches
     // in the same direction as the embellished operator.
     bool stretchAll = aStretchDirection == NS_STRETCH_DIRECTION_VERTICAL ?
                       NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY(mPresentationData.flags) :
                       NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY(mPresentationData.flags);
@@ -284,17 +284,17 @@ nsMathMLContainerFrame::GetPreferredStre
       }
       childFrame = childFrame->GetNextSibling();
     }
     aPreferredStretchSize = bm;
   }
 }
 
 NS_IMETHODIMP
-nsMathMLContainerFrame::Stretch(nsRenderingContext& aRenderingContext,
+nsMathMLContainerFrame::Stretch(DrawTarget*          aDrawTarget,
                                 nsStretchDirection   aStretchDirection,
                                 nsBoundingMetrics&   aContainerSize,
                                 nsHTMLReflowMetrics& aDesiredStretchSize)
 {
   if (NS_MATHML_IS_EMBELLISH_OPERATOR(mEmbellishData.flags)) {
 
     if (NS_MATHML_STRETCH_WAS_DONE(mPresentationData.flags)) {
       NS_WARNING("it is wrong to fire stretch more than once on a frame");
@@ -334,69 +334,69 @@ nsMathMLContainerFrame::Stretch(nsRender
         nsBoundingMetrics containerSize = aContainerSize;
         if (aStretchDirection != mEmbellishData.direction &&
             mEmbellishData.direction != NS_STRETCH_DIRECTION_UNSUPPORTED) {
           NS_ASSERTION(mEmbellishData.direction != NS_STRETCH_DIRECTION_DEFAULT,
                        "Stretches may have a default direction, operators can not.");
           if (mEmbellishData.direction == NS_STRETCH_DIRECTION_VERTICAL ?
               NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY(mPresentationData.flags) :
               NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY(mPresentationData.flags)) {
-            GetPreferredStretchSize(aRenderingContext, 0,
+            GetPreferredStretchSize(aDrawTarget, 0,
                                     mEmbellishData.direction, containerSize);
             // Stop further recalculations
             aStretchDirection = mEmbellishData.direction;
           } else {
             // We aren't going to stretch the child, so just use the child metrics.
             containerSize = childSize.mBoundingMetrics;
           }
         }
 
         // do the stretching...
-        mathMLFrame->Stretch(aRenderingContext,
+        mathMLFrame->Stretch(aDrawTarget,
                              aStretchDirection, containerSize, childSize);
         // store the updated metrics
         SaveReflowAndBoundingMetricsFor(baseFrame, childSize,
                                         childSize.mBoundingMetrics);
         
         // Remember the siblings which were _deferred_.
         // Now that this embellished child may have changed, we need to
         // fire the stretch on its siblings using our updated size
 
         if (NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY(mPresentationData.flags) ||
             NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY(mPresentationData.flags)) {
 
           nsStretchDirection stretchDir =
             NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY(mPresentationData.flags) ?
               NS_STRETCH_DIRECTION_VERTICAL : NS_STRETCH_DIRECTION_HORIZONTAL;
 
-          GetPreferredStretchSize(aRenderingContext, STRETCH_CONSIDER_EMBELLISHMENTS,
+          GetPreferredStretchSize(aDrawTarget, STRETCH_CONSIDER_EMBELLISHMENTS,
                                   stretchDir, containerSize);
 
           nsIFrame* childFrame = mFrames.FirstChild();
           while (childFrame) {
             if (childFrame != mPresentationData.baseFrame) {
               mathMLFrame = do_QueryFrame(childFrame);
               if (mathMLFrame) {
                 // retrieve the metrics that was stored at the previous pass
                 GetReflowAndBoundingMetricsFor(childFrame, 
                   childSize, childSize.mBoundingMetrics);
                 // do the stretching...
-                mathMLFrame->Stretch(aRenderingContext, stretchDir,
+                mathMLFrame->Stretch(aDrawTarget, stretchDir,
                                      containerSize, childSize);
                 // store the updated metrics
                 SaveReflowAndBoundingMetricsFor(childFrame, childSize,
                                                 childSize.mBoundingMetrics);
               }
             }
             childFrame = childFrame->GetNextSibling();
           }
         }
 
         // re-position all our children
-        nsresult rv = Place(aRenderingContext, true, aDesiredStretchSize);
+        nsresult rv = Place(aDrawTarget, true, aDesiredStretchSize);
         if (NS_MATHML_HAS_ERROR(mPresentationData.flags) || NS_FAILED(rv)) {
           // Make sure the child frames get their DidReflow() calls.
           DidReflowChildren(mFrames.FirstChild());
         }
 
         // If our parent is not embellished, it means we are the outermost embellished
         // container and so we put the spacing, otherwise we don't include the spacing,
         // the outermost embellished container will take care of it.
@@ -440,17 +440,17 @@ nsMathMLContainerFrame::Stretch(nsRender
         GatherAndStoreOverflow(&aDesiredStretchSize);
       }
     }
   }
   return NS_OK;
 }
 
 nsresult
-nsMathMLContainerFrame::FinalizeReflow(nsRenderingContext& aRenderingContext,
+nsMathMLContainerFrame::FinalizeReflow(DrawTarget* aDrawTarget,
                                        nsHTMLReflowMetrics& aDesiredSize)
 {
   // During reflow, we use rect.x and rect.y as placeholders for the child's ascent
   // and descent in expectation of a stretch command. Hence we need to ensure that
   // a stretch command will actually be fired later on, after exiting from our
   // reflow. If the stretch is not fired, the rect.x, and rect.y will remain
   // with inappropriate data causing children to be improperly positioned.
   // This helper method checks to see if our parent will fire a stretch command
@@ -467,17 +467,17 @@ nsMathMLContainerFrame::FinalizeReflow(n
   // The first clause caters for any non-embellished container.
   // The second clause is for a container which won't fire stretch even though it is
   // embellished, e.g., as in <mfrac><mo>...</mo> ... </mfrac>, the test is convoluted
   // because it excludes the particular case of the core <mo>...</mo> itself.
   // (<mo> needs to fire stretch on its MathMLChar in any case to initialize it)
   bool placeOrigin = !NS_MATHML_IS_EMBELLISH_OPERATOR(mEmbellishData.flags) ||
                        (mEmbellishData.coreFrame != this && !mPresentationData.baseFrame &&
                         mEmbellishData.direction == NS_STRETCH_DIRECTION_UNSUPPORTED);
-  nsresult rv = Place(aRenderingContext, placeOrigin, aDesiredSize);
+  nsresult rv = Place(aDrawTarget, placeOrigin, aDesiredSize);
 
   // Place() will call FinishReflowChild() when placeOrigin is true but if
   // it returns before reaching FinishReflowChild() due to errors we need
   // to fulfill the reflow protocol by calling DidReflow for the child frames
   // that still needs it here (or we may crash - bug 366012).
   // If placeOrigin is false we should reach Place() with aPlaceOrigin == true
   // through Stretch() eventually.
   if (NS_MATHML_HAS_ERROR(mPresentationData.flags) || NS_FAILED(rv)) {
@@ -521,18 +521,17 @@ nsMathMLContainerFrame::FinalizeReflow(n
       } else {
         // Let the Stretch() call decide the direction.
         stretchDir = NS_STRETCH_DIRECTION_DEFAULT;
       }
       // Use our current size as computed earlier by Place()
       // The stretch call will detect if this is incorrect and recalculate the size.
       nsBoundingMetrics defaultSize = aDesiredSize.mBoundingMetrics;
 
-      Stretch(aRenderingContext, stretchDir, defaultSize,
-              aDesiredSize);
+      Stretch(aDrawTarget, stretchDir, defaultSize, aDesiredSize);
 #ifdef DEBUG
       {
         // The Place() call above didn't request FinishReflowChild(),
         // so let's check that we eventually did through Stretch().
         nsIFrame* childFrame = GetFirstPrincipalChild();
         for ( ; childFrame; childFrame = childFrame->GetNextSibling()) {
           NS_ASSERTION(!(childFrame->GetStateBits() & NS_FRAME_IN_REFLOW),
                        "DidReflow() was never called");
@@ -869,17 +868,17 @@ nsMathMLContainerFrame::ReflowChild(nsIF
       // GetBaseline().  This is what nsFrame::GetBaseline() will do anyway.
       aDesiredSize.SetBlockStartAscent(aDesiredSize.BSize(wm));
     } else {
       aDesiredSize.SetBlockStartAscent(ascent);
     }
   }
   if (IsForeignChild(aChildFrame)) {
     // use ComputeTightBounds API as aDesiredSize.mBoundingMetrics is not set.
-    nsRect r = aChildFrame->ComputeTightBounds(aReflowState.rendContext->ThebesContext());
+    nsRect r = aChildFrame->ComputeTightBounds(aReflowState.rendContext->GetDrawTarget());
     aDesiredSize.mBoundingMetrics.leftBearing = r.x;
     aDesiredSize.mBoundingMetrics.rightBearing = r.XMost();
     aDesiredSize.mBoundingMetrics.ascent = aDesiredSize.BlockStartAscent() - r.y;
     aDesiredSize.mBoundingMetrics.descent = r.YMost() - aDesiredSize.BlockStartAscent();
     aDesiredSize.mBoundingMetrics.width = aDesiredSize.Width();
   }
 }
 
@@ -919,57 +918,58 @@ nsMathMLContainerFrame::Reflow(nsPresCon
 
   /////////////
   // If we are a container which is entitled to stretch its children, then we
   // ask our stretchy children to stretch themselves
 
   // The stretching of siblings of an embellished child is _deferred_ until
   // after finishing the stretching of the embellished child - bug 117652
 
+  DrawTarget* drawTarget = aReflowState.rendContext->GetDrawTarget();
+
   if (!NS_MATHML_IS_EMBELLISH_OPERATOR(mEmbellishData.flags) &&
       (NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY(mPresentationData.flags) ||
        NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY(mPresentationData.flags))) {
 
     // get the stretchy direction
     nsStretchDirection stretchDir =
       NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY(mPresentationData.flags) 
       ? NS_STRETCH_DIRECTION_VERTICAL 
       : NS_STRETCH_DIRECTION_HORIZONTAL;
 
     // what size should we use to stretch our stretchy children
     // We don't use STRETCH_CONSIDER_ACTUAL_SIZE -- because our size is not known yet
     // We don't use STRETCH_CONSIDER_EMBELLISHMENTS -- because we don't want to
     // include them in the caculations of the size of stretchy elements
     nsBoundingMetrics containerSize;
-    GetPreferredStretchSize(*aReflowState.rendContext, 0, stretchDir,
-                            containerSize);
+    GetPreferredStretchSize(drawTarget, 0, stretchDir, containerSize);
 
     // fire the stretch on each child
     childFrame = mFrames.FirstChild();
     while (childFrame) {
       nsIMathMLFrame* mathMLFrame = do_QueryFrame(childFrame);
       if (mathMLFrame) {
         // retrieve the metrics that was stored at the previous pass
         nsHTMLReflowMetrics childDesiredSize(aReflowState);
         GetReflowAndBoundingMetricsFor(childFrame,
           childDesiredSize, childDesiredSize.mBoundingMetrics);
 
-        mathMLFrame->Stretch(*aReflowState.rendContext, stretchDir,
+        mathMLFrame->Stretch(drawTarget, stretchDir,
                              containerSize, childDesiredSize);
         // store the updated metrics
         SaveReflowAndBoundingMetricsFor(childFrame, childDesiredSize,
                                         childDesiredSize.mBoundingMetrics);
       }
       childFrame = childFrame->GetNextSibling();
     }
   }
 
   /////////////
   // Place children now by re-adjusting the origins to align the baselines
-  FinalizeReflow(*aReflowState.rendContext, aDesiredSize);
+  FinalizeReflow(drawTarget, aDesiredSize);
 
   aStatus = NS_FRAME_COMPLETE;
   NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aDesiredSize);
 }
 
 static nscoord AddInterFrameSpacingToSize(nsHTMLReflowMetrics&    aDesiredSize,
                                           nsMathMLContainerFrame* aFrame);
 
@@ -1050,29 +1050,29 @@ nsMathMLContainerFrame::GetIntrinsicISiz
 
     SaveReflowAndBoundingMetricsFor(childFrame, childDesiredSize,
                                     childDesiredSize.mBoundingMetrics);
 
     childFrame = childFrame->GetNextSibling();
   }
 
   // Measure
-  nsresult rv = MeasureForWidth(*aRenderingContext, aDesiredSize);
+  nsresult rv = MeasureForWidth(aRenderingContext->GetDrawTarget(), aDesiredSize);
   if (NS_FAILED(rv)) {
-    ReflowError(*aRenderingContext, aDesiredSize);
+    ReflowError(aRenderingContext->GetDrawTarget(), aDesiredSize);
   }
 
   ClearSavedChildMetrics();
 }
 
 /* virtual */ nsresult
-nsMathMLContainerFrame::MeasureForWidth(nsRenderingContext& aRenderingContext,
+nsMathMLContainerFrame::MeasureForWidth(DrawTarget* aDrawTarget,
                                         nsHTMLReflowMetrics& aDesiredSize)
 {
-  return Place(aRenderingContext, false, aDesiredSize);
+  return Place(aDrawTarget, false, aDesiredSize);
 }
 
 
 // see spacing table in Chapter 18, TeXBook (p.170)
 // Our table isn't quite identical to TeX because operators have 
 // built-in values for lspace & rspace in the Operator Dictionary.
 static int32_t kInterFrameSpacingTable[eMathMLFrameType_COUNT][eMathMLFrameType_COUNT] =
 {
@@ -1273,17 +1273,17 @@ private:
     // add left correction -- this fixes the problem of the italic 'f'
     // e.g., <mo>q</mo> <mi>f</mi> <mo>I</mo> 
     mX += leftCorrection;
     mItalicCorrection = rightCorrection;
   }
 };
 
 /* virtual */ nsresult
-nsMathMLContainerFrame::Place(nsRenderingContext& aRenderingContext,
+nsMathMLContainerFrame::Place(DrawTarget*          aDrawTarget,
                               bool                 aPlaceOrigin,
                               nsHTMLReflowMetrics& aDesiredSize)
 {
   // This is needed in case this frame is empty (i.e., no child frames)
   mBoundingMetrics = nsBoundingMetrics();
 
   RowChildFrameIterator child(this);
   nscoord ascent = 0, descent = 0;
--- a/layout/mathml/nsMathMLContainerFrame.h
+++ b/layout/mathml/nsMathMLContainerFrame.h
@@ -39,17 +39,17 @@ public:
   NS_DECL_QUERYFRAME_TARGET(nsMathMLContainerFrame)
   NS_DECL_QUERYFRAME
   NS_DECL_ABSTRACT_FRAME(nsMathMLContainerFrame)
 
   // --------------------------------------------------------------------------
   // Overloaded nsMathMLFrame methods -- see documentation in nsIMathMLFrame.h
 
   NS_IMETHOD
-  Stretch(nsRenderingContext& aRenderingContext,
+  Stretch(DrawTarget*          aDrawTarget,
           nsStretchDirection   aStretchDirection,
           nsBoundingMetrics&   aContainerSize,
           nsHTMLReflowMetrics& aDesiredStretchSize) override;
 
   NS_IMETHOD
   UpdatePresentationDataFromChildAt(int32_t         aFirstIndex,
                                     int32_t         aLastIndex,
                                     uint32_t        aFlagsValues,
@@ -191,57 +191,56 @@ protected:
    *
    * @param aDesiredSize [out] parameter where you should return your desired
    *        size and your ascent/descent info. Compute your desired size using
    *        the information from GetReflowAndBoundingMetricsFor, and include
    *        any space you want for border/padding in the desired size you
    *        return.
    */
   virtual nsresult
-  Place(nsRenderingContext& aRenderingContext,
+  Place(DrawTarget*          aDrawTarget,
         bool                 aPlaceOrigin,
         nsHTMLReflowMetrics& aDesiredSize);
 
   // MeasureForWidth:
   //
   // A method used by nsMathMLContainerFrame::GetIntrinsicISize to get the
   // width that a particular Place method desires.  For most frames, this will
   // just call the object's Place method.  However <msqrt> and <menclose> use
   // nsMathMLContainerFrame::GetIntrinsicISize to measure the child frames as
   // if in an <mrow>, and so their frames implement MeasureForWidth to use
   // nsMathMLContainerFrame::Place.
   virtual nsresult
-  MeasureForWidth(nsRenderingContext& aRenderingContext,
+  MeasureForWidth(DrawTarget* aDrawTarget,
                   nsHTMLReflowMetrics& aDesiredSize);
 
 
   // helper to re-sync the automatic data in our children and notify our parent to
   // reflow us when changes (e.g., append/insert/remove) happen in our child list
   virtual nsresult
   ChildListChanged(int32_t aModType);
 
   // helper to get the preferred size that a container frame should use to fire
   // the stretch on its stretchy child frames.
   void
-  GetPreferredStretchSize(nsRenderingContext& aRenderingContext,
+  GetPreferredStretchSize(DrawTarget*          aDrawTarget,
                           uint32_t             aOptions,
                           nsStretchDirection   aStretchDirection,
                           nsBoundingMetrics&   aPreferredStretchSize);
 
   // helper used by mstyle, mphantom, mpadded and mrow in their implementation
   // of TransmitAutomaticData() to determine whether they are space-like.
   nsresult
   TransmitAutomaticDataForMrowLikeElement();
 
 public:
   // error handlers to provide a visual feedback to the user when an error
   // (typically invalid markup) was encountered during reflow.
   nsresult
-  ReflowError(nsRenderingContext& aRenderingContext,
-              nsHTMLReflowMetrics& aDesiredSize);
+  ReflowError(DrawTarget* aDrawTarget, nsHTMLReflowMetrics& aDesiredSize);
   /*
    * Helper to call ReportErrorToConsole for parse errors involving 
    * attribute/value pairs.
    * @param aAttribute The attribute for which the parse error occured.
    * @param aValue The value for which the parse error occured.
    */
   nsresult
   ReportParseError(const char16_t*           aAttribute,
@@ -290,18 +289,17 @@ protected:
   // emulate the spacing that would have been done by a <mrow> container.
   // e.g., it fixes <math> <mi>f</mi> <mo>q</mo> <mi>f</mi> <mo>I</mo> </math>
   virtual nscoord
   FixInterFrameSpacing(nsHTMLReflowMetrics& aDesiredSize);
 
   // helper method to complete the post-reflow hook and ensure that embellished
   // operators don't terminate their Reflow without receiving a Stretch command.
   virtual nsresult
-  FinalizeReflow(nsRenderingContext& aRenderingContext,
-                 nsHTMLReflowMetrics& aDesiredSize);
+  FinalizeReflow(DrawTarget* aDrawTarget, nsHTMLReflowMetrics& aDesiredSize);
 
   // Record metrics of a child frame for recovery through the following method
   static void
   SaveReflowAndBoundingMetricsFor(nsIFrame*                  aFrame,
                                   const nsHTMLReflowMetrics& aReflowMetrics,
                                   const nsBoundingMetrics&   aBoundingMetrics);
 
   // helper method to facilitate getting the reflow and bounding metrics of a
--- a/layout/mathml/nsMathMLFrame.cpp
+++ b/layout/mathml/nsMathMLFrame.cpp
@@ -163,50 +163,49 @@ nsMathMLFrame::GetPresentationDataFrom(n
     }
     frame = frame->GetParent();
   }
   NS_WARN_IF_FALSE(frame && frame->GetContent(),
                    "bad MathML markup - could not find the top <math> element");
 }
 
 /* static */ void
-nsMathMLFrame::GetRuleThickness(nsRenderingContext& aRenderingContext,
-                                nsFontMetrics*      aFontMetrics,
-                                nscoord&             aRuleThickness)
+nsMathMLFrame::GetRuleThickness(DrawTarget*    aDrawTarget,
+                                nsFontMetrics* aFontMetrics,
+                                nscoord&       aRuleThickness)
 {
   nscoord xHeight = aFontMetrics->XHeight();
   char16_t overBar = 0x00AF;
   nsBoundingMetrics bm =
     nsLayoutUtils::AppUnitBoundsOfString(&overBar, 1, *aFontMetrics,
-                                         aRenderingContext);
+                                         aDrawTarget);
   aRuleThickness = bm.ascent + bm.descent;
   if (aRuleThickness <= 0 || aRuleThickness >= xHeight) {
     // fall-back to the other version
     GetRuleThickness(aFontMetrics, aRuleThickness);
   }
 }
 
 /* static */ void
-nsMathMLFrame::GetAxisHeight(nsRenderingContext& aRenderingContext,
-                             nsFontMetrics*      aFontMetrics,
-                             nscoord&             aAxisHeight)
+nsMathMLFrame::GetAxisHeight(DrawTarget*    aDrawTarget,
+                             nsFontMetrics* aFontMetrics,
+                             nscoord&       aAxisHeight)
 {
   gfxFont* mathFont = aFontMetrics->GetThebesFontGroup()->GetFirstMathFont();
   if (mathFont) {
     aAxisHeight =
       mathFont->GetMathConstant(gfxFontEntry::AxisHeight,
                                 aFontMetrics->AppUnitsPerDevPixel());
     return;
   }
 
   nscoord xHeight = aFontMetrics->XHeight();
   char16_t minus = 0x2212; // not '-', but official Unicode minus sign
   nsBoundingMetrics bm =
-    nsLayoutUtils::AppUnitBoundsOfString(&minus, 1, *aFontMetrics,
-                                         aRenderingContext);
+    nsLayoutUtils::AppUnitBoundsOfString(&minus, 1, *aFontMetrics, aDrawTarget);
   aAxisHeight = bm.ascent - (bm.ascent + bm.descent)/2;
   if (aAxisHeight <= 0 || aAxisHeight >= xHeight) {
     // fall-back to the other version
     GetAxisHeight(aFontMetrics, aAxisHeight);
   }
 }
 
 /* static */ nscoord
--- a/layout/mathml/nsMathMLFrame.h
+++ b/layout/mathml/nsMathMLFrame.h
@@ -16,17 +16,16 @@
 
 class nsMathMLChar;
 class nsCSSValue;
 class nsDisplayListSet;
 
 // Concrete base class with default methods that derived MathML frames can override
 class nsMathMLFrame : public nsIMathMLFrame {
 public:
-
   // nsIMathMLFrame ---
 
   virtual bool
   IsSpaceLike() override {
     return NS_MATHML_IS_SPACE_LIKE(mPresentationData.flags);
   }
 
   NS_IMETHOD
@@ -45,17 +44,17 @@ public:
   SetReference(const nsPoint& aReference) override {
     mReference = aReference;
     return NS_OK;
   }
 
   virtual eMathMLFrameType GetMathMLFrameType() override;
 
   NS_IMETHOD
-  Stretch(nsRenderingContext& aRenderingContext,
+  Stretch(mozilla::gfx::DrawTarget* aDrawTarget,
           nsStretchDirection   aStretchDirection,
           nsBoundingMetrics&   aContainerSize,
           nsHTMLReflowMetrics& aDesiredStretchSize) override
   {
     return NS_OK;
   }
 
   NS_IMETHOD
@@ -331,24 +330,24 @@ public:
     nscoord xHeight = fm->XHeight();
     ruleThickness = NSToCoordRound(40.000f/430.556f * xHeight);
   }
 
   // Some parameters are not accurately obtained using the x-height.
   // Here are some slower variants to obtain the desired metrics
   // by actually measuring some characters
   static void
-  GetRuleThickness(nsRenderingContext& aRenderingContext, 
-                   nsFontMetrics*      aFontMetrics,
-                   nscoord&             aRuleThickness);
+  GetRuleThickness(mozilla::gfx::DrawTarget* aDrawTarget,
+                   nsFontMetrics* aFontMetrics,
+                   nscoord& aRuleThickness);
 
   static void
-  GetAxisHeight(nsRenderingContext& aRenderingContext, 
-                nsFontMetrics*      aFontMetrics,
-                nscoord&             aAxisHeight);
+  GetAxisHeight(mozilla::gfx::DrawTarget* aDrawTarget,
+                nsFontMetrics* aFontMetrics,
+                nscoord& aAxisHeight);
 
   static void
   GetRadicalParameters(nsFontMetrics* aFontMetrics,
                        bool aDisplayStyle,
                        nscoord& aRadicalRuleThickness,
                        nscoord& aRadicalExtraAscender,
                        nscoord& aRadicalVerticalGap);
 
--- a/layout/mathml/nsMathMLSelectedFrame.cpp
+++ b/layout/mathml/nsMathMLSelectedFrame.cpp
@@ -152,30 +152,30 @@ nsMathMLSelectedFrame::Reflow(nsPresCont
     nsHTMLReflowState childReflowState(aPresContext, aReflowState,
                                        childFrame, availSize);
     ReflowChild(childFrame, aPresContext, aDesiredSize,
                 childReflowState, aStatus);
     SaveReflowAndBoundingMetricsFor(childFrame, aDesiredSize,
                                     aDesiredSize.mBoundingMetrics);
     mBoundingMetrics = aDesiredSize.mBoundingMetrics;
   }
-  FinalizeReflow(*aReflowState.rendContext, aDesiredSize);
+  FinalizeReflow(aReflowState.rendContext->GetDrawTarget(), aDesiredSize);
   NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aDesiredSize);
 }
 
 // Only place the selected child ...
 /* virtual */ nsresult
-nsMathMLSelectedFrame::Place(nsRenderingContext& aRenderingContext,
+nsMathMLSelectedFrame::Place(DrawTarget*          aDrawTarget,
                              bool                 aPlaceOrigin,
                              nsHTMLReflowMetrics& aDesiredSize)
 {
   nsIFrame* childFrame = GetSelectedFrame();
 
   if (mInvalidMarkup) {
-    return ReflowError(aRenderingContext, aDesiredSize);
+    return ReflowError(aDrawTarget, aDesiredSize);
   }
 
   aDesiredSize.ClearSize();
   aDesiredSize.SetBlockStartAscent(0);
   mBoundingMetrics = nsBoundingMetrics();
   if (childFrame) {
     GetReflowAndBoundingMetricsFor(childFrame, aDesiredSize, mBoundingMetrics);
     if (aPlaceOrigin) {
--- a/layout/mathml/nsMathMLSelectedFrame.h
+++ b/layout/mathml/nsMathMLSelectedFrame.h
@@ -25,17 +25,17 @@ public:
   virtual nsresult
   ChildListChanged(int32_t aModType) override;
 
   virtual void BuildDisplayList(nsDisplayListBuilder*   aBuilder,
                                 const nsRect&           aDirtyRect,
                                 const nsDisplayListSet& aLists) override;
 
   virtual nsresult
-  Place(nsRenderingContext& aRenderingContext,
+  Place(DrawTarget*          aDrawTarget,
         bool                 aPlaceOrigin,
         nsHTMLReflowMetrics& aDesiredSize) override;
 
   virtual mozilla::LogicalSize
   ComputeSize(nsRenderingContext *aRenderingContext,
               mozilla::WritingMode aWritingMode,
               const mozilla::LogicalSize& aCBSize,
               nscoord aAvailableISize,
--- a/layout/mathml/nsMathMLTokenFrame.cpp
+++ b/layout/mathml/nsMathMLTokenFrame.cpp
@@ -148,27 +148,27 @@ nsMathMLTokenFrame::Reflow(nsPresContext
     //NS_ASSERTION(NS_FRAME_IS_COMPLETE(aStatus), "bad status");
     SaveReflowAndBoundingMetricsFor(childFrame, childDesiredSize,
                                     childDesiredSize.mBoundingMetrics);
 
     childFrame = childFrame->GetNextSibling();
   }
 
   // place and size children
-  FinalizeReflow(*aReflowState.rendContext, aDesiredSize);
+  FinalizeReflow(aReflowState.rendContext->GetDrawTarget(), aDesiredSize);
 
   aStatus = NS_FRAME_COMPLETE;
   NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aDesiredSize);
 }
 
 // For token elements, mBoundingMetrics is computed at the ReflowToken
 // pass, it is not computed here because our children may be text frames
 // that do not implement the GetBoundingMetrics() interface.
 /* virtual */ nsresult
-nsMathMLTokenFrame::Place(nsRenderingContext& aRenderingContext,
+nsMathMLTokenFrame::Place(DrawTarget*          aDrawTarget,
                           bool                 aPlaceOrigin,
                           nsHTMLReflowMetrics& aDesiredSize)
 {
   mBoundingMetrics = nsBoundingMetrics();
   for (nsIFrame* childFrame = GetFirstPrincipalChild(); childFrame;
        childFrame = childFrame->GetNextSibling()) {
     nsHTMLReflowMetrics childSize(aDesiredSize.GetWritingMode());
     GetReflowAndBoundingMetricsFor(childFrame, childSize,
--- a/layout/mathml/nsMathMLTokenFrame.h
+++ b/layout/mathml/nsMathMLTokenFrame.h
@@ -49,17 +49,17 @@ public:
 
   virtual void
   Reflow(nsPresContext*          aPresContext,
          nsHTMLReflowMetrics&     aDesiredSize,
          const nsHTMLReflowState& aReflowState,
          nsReflowStatus&          aStatus) override;
 
   virtual nsresult
-  Place(nsRenderingContext& aRenderingContext,
+  Place(DrawTarget*          aDrawTarget,
         bool                 aPlaceOrigin,
         nsHTMLReflowMetrics& aDesiredSize) override;
 
 protected:
   explicit nsMathMLTokenFrame(nsStyleContext* aContext) : nsMathMLContainerFrame(aContext) {}
   virtual ~nsMathMLTokenFrame();
 
   void MarkTextFramesAsTokenMathML();
--- a/layout/mathml/nsMathMLmencloseFrame.cpp
+++ b/layout/mathml/nsMathMLmencloseFrame.cpp
@@ -294,42 +294,42 @@ nsMathMLmencloseFrame::BuildDisplayList(
   if (IsToDraw(NOTATION_VERTICALSTRIKE)) {
     nsRect rect(mencloseRect.width / 2 - mRuleThickness / 2, 0,
                 mRuleThickness, mencloseRect.height);
     DisplayBar(aBuilder, this, rect, aLists);
   }
 }
 
 /* virtual */ nsresult
-nsMathMLmencloseFrame::MeasureForWidth(nsRenderingContext& aRenderingContext,
+nsMathMLmencloseFrame::MeasureForWidth(DrawTarget* aDrawTarget,
                                        nsHTMLReflowMetrics& aDesiredSize)
 {
-  return PlaceInternal(aRenderingContext, false, aDesiredSize, true);
+  return PlaceInternal(aDrawTarget, false, aDesiredSize, true);
 }
 
 /* virtual */ nsresult
-nsMathMLmencloseFrame::Place(nsRenderingContext& aRenderingContext,
+nsMathMLmencloseFrame::Place(DrawTarget*          aDrawTarget,
                              bool                 aPlaceOrigin,
                              nsHTMLReflowMetrics& aDesiredSize)
 {
-  return PlaceInternal(aRenderingContext, aPlaceOrigin, aDesiredSize, false);
+  return PlaceInternal(aDrawTarget, aPlaceOrigin, aDesiredSize, false);
 }
 
 /* virtual */ nsresult
-nsMathMLmencloseFrame::PlaceInternal(nsRenderingContext& aRenderingContext,
+nsMathMLmencloseFrame::PlaceInternal(DrawTarget*          aDrawTarget,
                                      bool                 aPlaceOrigin,
                                      nsHTMLReflowMetrics& aDesiredSize,
                                      bool                 aWidthOnly)
 {
   ///////////////
   // Measure the size of our content using the base class to format like an
   // inferred mrow.
   nsHTMLReflowMetrics baseSize(aDesiredSize.GetWritingMode());
   nsresult rv =
-    nsMathMLContainerFrame::Place(aRenderingContext, false, baseSize);
+    nsMathMLContainerFrame::Place(aDrawTarget, false, baseSize);
 
   if (NS_MATHML_HAS_ERROR(mPresentationData.flags) || NS_FAILED(rv)) {
       DidReflowChildren(GetFirstPrincipalChild());
       return rv;
     }
 
   nsBoundingMetrics bmBase = baseSize.mBoundingMetrics;
   nscoord dx_left = 0, dx_right = 0;
@@ -342,24 +342,24 @@ nsMathMLmencloseFrame::PlaceInternal(nsR
   ///////////////
   // Thickness of bars and font metrics
   nscoord onePixel = nsPresContext::CSSPixelsToAppUnits(1);
 
   float fontSizeInflation = nsLayoutUtils::FontSizeInflationFor(this);
   RefPtr<nsFontMetrics> fm;
   nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
                                         fontSizeInflation);
-  GetRuleThickness(aRenderingContext, fm, mRuleThickness);
+  GetRuleThickness(aDrawTarget, fm, mRuleThickness);
   if (mRuleThickness < onePixel) {
     mRuleThickness = onePixel;
   }
 
   char16_t one = '1';
   nsBoundingMetrics bmOne =
-    nsLayoutUtils::AppUnitBoundsOfString(&one, 1, *fm, aRenderingContext);
+    nsLayoutUtils::AppUnitBoundsOfString(&one, 1, *fm, aDrawTarget);
 
   ///////////////
   // General rules: the menclose element takes the size of the enclosed content.
   // We add a padding when needed.
 
   // determine padding & psi
   nscoord padding = 3 * mRuleThickness;
   nscoord delta = padding % onePixel;
@@ -479,29 +479,29 @@ nsMathMLmencloseFrame::PlaceInternal(nsR
                                       bmBase.descent + padding2);
   }
 
   ///////////////
   // longdiv notation:
   if (IsToDraw(NOTATION_LONGDIV)) {
     if (aWidthOnly) {
         nscoord longdiv_width = mMathMLChar[mLongDivCharIndex].
-          GetMaxWidth(PresContext(), aRenderingContext, fontSizeInflation);
+          GetMaxWidth(PresContext(), aDrawTarget, fontSizeInflation);
 
         // Update horizontal parameters
         dx_left = std::max(dx_left, longdiv_width);
     } else {
       // Stretch the parenthesis to the appropriate height if it is not
       // big enough.
       nsBoundingMetrics contSize = bmBase;
       contSize.ascent = mRuleThickness;
       contSize.descent = bmBase.ascent + bmBase.descent + psi;
 
       // height(longdiv) should be >= height(base) + psi + mRuleThickness
-      mMathMLChar[mLongDivCharIndex].Stretch(PresContext(), aRenderingContext,
+      mMathMLChar[mLongDivCharIndex].Stretch(PresContext(), aDrawTarget,
                                              fontSizeInflation,
                                              NS_STRETCH_DIRECTION_VERTICAL,
                                              contSize, bmLongdivChar,
                                              NS_STRETCH_LARGER, false);
       mMathMLChar[mLongDivCharIndex].GetBoundingMetrics(bmLongdivChar);
 
       // Update horizontal parameters
       dx_left = std::max(dx_left, bmLongdivChar.width);
@@ -521,29 +521,29 @@ nsMathMLmencloseFrame::PlaceInternal(nsR
 
   ///////////////
   // radical notation:
   if (IsToDraw(NOTATION_RADICAL)) {
     nscoord *dx_leading = StyleVisibility()->mDirection ? &dx_right : &dx_left;
     
     if (aWidthOnly) {
       nscoord radical_width = mMathMLChar[mRadicalCharIndex].
-        GetMaxWidth(PresContext(), aRenderingContext, fontSizeInflation);
+        GetMaxWidth(PresContext(), aDrawTarget, fontSizeInflation);
       
       // Update horizontal parameters
       *dx_leading = std::max(*dx_leading, radical_width);
     } else {
       // Stretch the radical symbol to the appropriate height if it is not
       // big enough.
       nsBoundingMetrics contSize = bmBase;
       contSize.ascent = mRadicalRuleThickness;
       contSize.descent = bmBase.ascent + bmBase.descent + psi;
 
       // height(radical) should be >= height(base) + psi + mRadicalRuleThickness
-      mMathMLChar[mRadicalCharIndex].Stretch(PresContext(), aRenderingContext,
+      mMathMLChar[mRadicalCharIndex].Stretch(PresContext(), aDrawTarget,
                                              fontSizeInflation,
                                              NS_STRETCH_DIRECTION_VERTICAL,
                                              contSize, bmRadicalChar,
                                              NS_STRETCH_LARGER,
                                              StyleVisibility()->mDirection);
       mMathMLChar[mRadicalCharIndex].GetBoundingMetrics(bmRadicalChar);
 
       // Update horizontal parameters
--- a/layout/mathml/nsMathMLmencloseFrame.h
+++ b/layout/mathml/nsMathMLmencloseFrame.h
@@ -45,22 +45,22 @@ enum nsMencloseNotation
 class nsMathMLmencloseFrame : public nsMathMLContainerFrame {
 public:
   NS_DECL_FRAMEARENA_HELPERS
 
   friend nsIFrame* NS_NewMathMLmencloseFrame(nsIPresShell*   aPresShell,
                                              nsStyleContext* aContext);
   
   virtual nsresult
-  Place(nsRenderingContext& aRenderingContext,
+  Place(DrawTarget*          aDrawTarget,
         bool                 aPlaceOrigin,
         nsHTMLReflowMetrics& aDesiredSize) override;
   
   virtual nsresult
-  MeasureForWidth(nsRenderingContext& aRenderingContext,
+  MeasureForWidth(DrawTarget* aDrawTarget,
                   nsHTMLReflowMetrics& aDesiredSize) override;
   
   virtual nsresult
   AttributeChanged(int32_t         aNameSpaceID,
                    nsIAtom*        aAttribute,
                    int32_t         aModType) override;
   
   virtual void
@@ -87,21 +87,21 @@ public:
     return mFrames.FirstChild() != mFrames.LastChild() ||
            !mFrames.FirstChild();
   }
 
 protected:
   explicit nsMathMLmencloseFrame(nsStyleContext* aContext);
   virtual ~nsMathMLmencloseFrame();
 
-  nsresult PlaceInternal(nsRenderingContext& aRenderingContext,
+  nsresult PlaceInternal(DrawTarget*          aDrawTarget,
                          bool                 aPlaceOrigin,
                          nsHTMLReflowMetrics& aDesiredSize,
                          bool                 aWidthOnly);
-  
+
   // functions to parse the "notation" attribute.
   nsresult AddNotation(const nsAString& aNotation);
   void InitNotations();
 
   // Description of the notations to draw
   uint32_t mNotationsToDraw;
   bool IsToDraw(nsMencloseNotation mask)
   {
--- a/layout/mathml/nsMathMLmfencedFrame.cpp
+++ b/layout/mathml/nsMathMLmfencedFrame.cpp
@@ -187,26 +187,25 @@ nsMathMLmfencedFrame::BuildDisplayList(n
 /* @param aMetrics is an IN/OUT.  Provide the current metrics for the mFenced
           frame and it will be enlarged as necessary.
 For simplicity the width of the container is always incremented by the width
 of the nsMathMLChar.  As we only stretch fences and separators in the vertical
 direction, this has no impact on overall appearance.
 */
 static void
 ApplyUnstretchedMetrics(nsPresContext*      aPresContext,
-                        nsRenderingContext& aRenderingContext,
+                        DrawTarget*         aDrawTarget,
                         float               aFontSizeInflation,
                         nsMathMLChar*       aMathMLChar,
                         nsBoundingMetrics&  aMetrics,
                         bool                aIsRTL)
 {
   if (aMathMLChar && 0 < aMathMLChar->Length()) {
     nsBoundingMetrics charSize;
-    aMathMLChar->Stretch(aPresContext, aRenderingContext,
-                         aFontSizeInflation,
+    aMathMLChar->Stretch(aPresContext, aDrawTarget, aFontSizeInflation,
                          NS_STRETCH_DIRECTION_DEFAULT,
                          aMetrics, // size is unimportant as we aren't stretching
                          charSize, NS_STRETCH_NONE, aIsRTL);
     aMetrics += charSize;
   }
 }
 
 void
@@ -223,17 +222,17 @@ nsMathMLmfencedFrame::Reflow(nsPresConte
 
   int32_t i;
   const nsStyleFont* font = StyleFont();
   float fontSizeInflation = nsLayoutUtils::FontSizeInflationFor(this);
   RefPtr<nsFontMetrics> fm;
   nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
                                         fontSizeInflation);
   nscoord axisHeight, em;
-  GetAxisHeight(*aReflowState.rendContext, fm, axisHeight);
+  GetAxisHeight(aReflowState.rendContext->GetDrawTarget(), fm, axisHeight);
   GetEmHeight(fm, em);
   // leading to be left at the top and the bottom of stretched chars
   nscoord leading = NSToCoordRound(0.2f * em); 
 
   /////////////
   // Reflow children
   // Asking each child to cache its bounding metrics
 
@@ -283,91 +282,92 @@ nsMathMLmfencedFrame::Reflow(nsPresConte
   }
 
   /////////////
   // Ask stretchy children to stretch themselves
 
   nsBoundingMetrics containerSize;
   nsStretchDirection stretchDir = NS_STRETCH_DIRECTION_VERTICAL;
 
-  GetPreferredStretchSize(*aReflowState.rendContext,
+  DrawTarget* drawTarget = aReflowState.rendContext->GetDrawTarget();
+
+  GetPreferredStretchSize(drawTarget,
                           0, /* i.e., without embellishments */
                           stretchDir, containerSize);
   childFrame = firstChild;
   while (childFrame) {
     nsIMathMLFrame* mathmlChild = do_QueryFrame(childFrame);
     if (mathmlChild) {
       nsHTMLReflowMetrics childDesiredSize(aReflowState);
       // retrieve the metrics that was stored at the previous pass
       GetReflowAndBoundingMetricsFor(childFrame, childDesiredSize,
                                      childDesiredSize.mBoundingMetrics);
-      
-      mathmlChild->Stretch(*aReflowState.rendContext, 
+
+      mathmlChild->Stretch(drawTarget,
                            stretchDir, containerSize, childDesiredSize);
       // store the updated metrics
       SaveReflowAndBoundingMetricsFor(childFrame, childDesiredSize,
                                       childDesiredSize.mBoundingMetrics);
-      
+
       nscoord childDescent = childDesiredSize.Height() - childDesiredSize.BlockStartAscent();
       if (descent < childDescent)
         descent = childDescent;
       if (ascent < childDesiredSize.BlockStartAscent())
         ascent = childDesiredSize.BlockStartAscent();
     }
     childFrame = childFrame->GetNextSibling();
   }
 
   // bug 121748: for surrounding fences & separators, use a size that covers everything
-  GetPreferredStretchSize(*aReflowState.rendContext,
-                          STRETCH_CONSIDER_EMBELLISHMENTS,
+  GetPreferredStretchSize(drawTarget, STRETCH_CONSIDER_EMBELLISHMENTS,
                           stretchDir, containerSize);
 
   bool isRTL = StyleVisibility()->mDirection;
 
   // To achieve a minimum size of "1", the container should be enlarged by the
   // unstretched metrics of the fences and separators.
-  ApplyUnstretchedMetrics(aPresContext, *aReflowState.rendContext,
+  ApplyUnstretchedMetrics(aPresContext, drawTarget,
                           fontSizeInflation, mOpenChar,
                           containerSize, isRTL);
   for (i = 0; i < mSeparatorsCount; i++) {
-    ApplyUnstretchedMetrics(aPresContext, *aReflowState.rendContext,
+    ApplyUnstretchedMetrics(aPresContext, drawTarget,
                             fontSizeInflation, &mSeparatorsChar[i],
                             containerSize, isRTL);
   }
-  ApplyUnstretchedMetrics(aPresContext, *aReflowState.rendContext,
+  ApplyUnstretchedMetrics(aPresContext, drawTarget,
                           fontSizeInflation, mCloseChar,
                           containerSize, isRTL);
 
   //////////////////////////////////////////
   // Prepare the opening fence, separators, and closing fence, and
   // adjust the origin of children.
 
   // we need to center around the axis
   nscoord delta = std::max(containerSize.ascent - axisHeight, 
                          containerSize.descent + axisHeight);
   containerSize.ascent = delta + axisHeight;
   containerSize.descent = delta - axisHeight;
 
   /////////////////
   // opening fence ...
-  ReflowChar(aPresContext, *aReflowState.rendContext, *fm,
+  ReflowChar(aPresContext, drawTarget, *fm,
              fontSizeInflation, mOpenChar,
              NS_MATHML_OPERATOR_FORM_PREFIX, font->mScriptLevel, 
              axisHeight, leading, em, containerSize, ascent, descent, isRTL);
   /////////////////
   // separators ...
   for (i = 0; i < mSeparatorsCount; i++) {
-    ReflowChar(aPresContext, *aReflowState.rendContext, *fm,
+    ReflowChar(aPresContext, drawTarget, *fm,
                fontSizeInflation, &mSeparatorsChar[i],
                NS_MATHML_OPERATOR_FORM_INFIX, font->mScriptLevel,
                axisHeight, leading, em, containerSize, ascent, descent, isRTL);
   }
   /////////////////
   // closing fence ...
-  ReflowChar(aPresContext, *aReflowState.rendContext, *fm,
+  ReflowChar(aPresContext, drawTarget, *fm,
              fontSizeInflation, mCloseChar,
              NS_MATHML_OPERATOR_FORM_POSTFIX, font->mScriptLevel,
              axisHeight, leading, em, containerSize, ascent, descent, isRTL);
 
   //////////////////
   // Adjust the origins of each child.
   // and update our bounding metrics
 
@@ -474,18 +474,18 @@ GetCharSpacing(nsMathMLChar*        aMat
   }
 
   aLeftSpace = NSToCoordRound(lspace * em);
   aRightSpace = NSToCoordRound(rspace * em);
 }
 
 // helper functions to perform the common task of formatting our chars
 /*static*/ nsresult
-nsMathMLmfencedFrame::ReflowChar(nsPresContext*      aPresContext,
-                                 nsRenderingContext& aRenderingContext,
+nsMathMLmfencedFrame::ReflowChar(nsPresContext*       aPresContext,
+                                 DrawTarget*          aDrawTarget,
                                  nsFontMetrics&       aFontMetrics,
                                  float                aFontSizeInflation,
                                  nsMathMLChar*        aMathMLChar,
                                  nsOperatorFlags      aForm,
                                  int32_t              aScriptLevel,
                                  nscoord              axisHeight,
                                  nscoord              leading,
                                  nscoord              em,
@@ -496,17 +496,17 @@ nsMathMLmfencedFrame::ReflowChar(nsPresC
 {
   if (aMathMLChar && 0 < aMathMLChar->Length()) {
     nscoord leftSpace;
     nscoord rightSpace;
     GetCharSpacing(aMathMLChar, aForm, aScriptLevel, em, leftSpace, rightSpace);
 
     // stretch the char to the appropriate height if it is not big enough.
     nsBoundingMetrics charSize;
-    nsresult res = aMathMLChar->Stretch(aPresContext, aRenderingContext,
+    nsresult res = aMathMLChar->Stretch(aPresContext, aDrawTarget,
                                         aFontSizeInflation,
                                         NS_STRETCH_DIRECTION_VERTICAL,
                                         aContainerSize, charSize,
                                         NS_STRETCH_NORMAL, aRTL);
 
     if (NS_STRETCH_DIRECTION_UNSUPPORTED != aMathMLChar->GetStretchDirection()) {
       // has changed... so center the char around the axis
       nscoord height = charSize.ascent + charSize.descent;
@@ -517,17 +517,17 @@ nsMathMLmfencedFrame::ReflowChar(nsPresC
       // either it hasn't changed or stretching the char failed (i.e.,
       // nsLayoutUtils::AppUnitBoundsOfString failed)
       leading = 0;
       if (NS_FAILED(res)) {
         nsAutoString data;
         aMathMLChar->GetData(data);
         nsBoundingMetrics metrics =
           nsLayoutUtils::AppUnitBoundsOfString(data.get(), data.Length(),
-                                               aFontMetrics, aRenderingContext);
+                                               aFontMetrics, aDrawTarget);
         charSize.ascent = metrics.ascent;
         charSize.descent = metrics.descent;
         charSize.width = metrics.width;
         // Set this as the bounding metrics of the MathMLChar to leave
         // the necessary room to paint the char.
         aMathMLChar->SetBoundingMetrics(charSize);
       }
     }
@@ -578,24 +578,24 @@ nsMathMLmfencedFrame::PlaceChar(nsMathML
 
   // return rect.width since it includes lspace and rspace
   bm.width = rect.width;
   dx += rect.width;
 }
 
 static nscoord
 GetMaxCharWidth(nsPresContext*       aPresContext,
-                nsRenderingContext* aRenderingContext,
+                DrawTarget*          aDrawTarget,
                 float                aFontSizeInflation,
                 nsMathMLChar*        aMathMLChar,
                 nsOperatorFlags      aForm,
                 int32_t              aScriptLevel,
                 nscoord              em)
 {
-  nscoord width = aMathMLChar->GetMaxWidth(aPresContext, *aRenderingContext,
+  nscoord width = aMathMLChar->GetMaxWidth(aPresContext, aDrawTarget,
                                            aFontSizeInflation);
 
   if (0 < aMathMLChar->Length()) {
     nscoord leftSpace;
     nscoord rightSpace;
     GetCharSpacing(aMathMLChar, aForm, aScriptLevel, em, leftSpace, rightSpace);
 
     width += leftSpace + rightSpace;
@@ -615,44 +615,44 @@ nsMathMLmfencedFrame::GetIntrinsicISizeM
   RefPtr<nsFontMetrics> fm;
   nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
                                         fontSizeInflation);
   nscoord em;
   GetEmHeight(fm, em);
 
   if (mOpenChar) {
     width +=
-      GetMaxCharWidth(presContext, aRenderingContext,
+      GetMaxCharWidth(presContext, aRenderingContext->GetDrawTarget(),
                       fontSizeInflation, mOpenChar,
                       NS_MATHML_OPERATOR_FORM_PREFIX, font->mScriptLevel, em);
   }
 
   int32_t i = 0;
   nsIFrame* childFrame = GetFirstPrincipalChild();
   while (childFrame) {
     // XXX This includes margin while Reflow currently doesn't consider
     // margin, so we may end up with too much space, but, with stretchy
     // characters, this is an approximation anyway.
     width += nsLayoutUtils::IntrinsicForContainer(aRenderingContext, childFrame,
                                                   nsLayoutUtils::PREF_ISIZE);
 
     if (i < mSeparatorsCount) {
       width +=
-        GetMaxCharWidth(presContext, aRenderingContext,
+        GetMaxCharWidth(presContext, aRenderingContext->GetDrawTarget(),
                         fontSizeInflation, &mSeparatorsChar[i],
                         NS_MATHML_OPERATOR_FORM_INFIX, font->mScriptLevel, em);
     }
     i++;
 
     childFrame = childFrame->GetNextSibling();
   }
 
   if (mCloseChar) {
     width +=
-      GetMaxCharWidth(presContext, aRenderingContext,
+      GetMaxCharWidth(presContext, aRenderingContext->GetDrawTarget(),
                       fontSizeInflation, mCloseChar,
                       NS_MATHML_OPERATOR_FORM_POSTFIX, font->mScriptLevel, em);
   }
 
   aDesiredSize.Width() = width;
   aDesiredSize.mBoundingMetrics.width = width;
   aDesiredSize.mBoundingMetrics.leftBearing = 0;
   aDesiredSize.mBoundingMetrics.rightBearing = width;
--- a/layout/mathml/nsMathMLmfencedFrame.h
+++ b/layout/mathml/nsMathMLmfencedFrame.h
@@ -58,18 +58,18 @@ public:
   ChildListChanged(int32_t aModType) override;
 
   // override the base method so that we can deal with fences and separators
   virtual nscoord
   FixInterFrameSpacing(nsHTMLReflowMetrics& aDesiredSize) override;
 
   // helper routines to format the MathMLChars involved here
   static nsresult
-  ReflowChar(nsPresContext*      aPresContext,
-             nsRenderingContext& aRenderingContext,
+  ReflowChar(nsPresContext*       aPresContext,
+             DrawTarget*          aDrawTarget,
              nsFontMetrics&       aFontMetrics,
              float                aFontSizeInflation,
              nsMathMLChar*        aMathMLChar,
              nsOperatorFlags      aForm,
              int32_t              aScriptLevel,
              nscoord              axisHeight,
              nscoord              leading,
              nscoord              em,
--- a/layout/mathml/nsMathMLmfracFrame.cpp
+++ b/layout/mathml/nsMathMLmfracFrame.cpp
@@ -160,48 +160,42 @@ nsMathMLmfracFrame::BuildDisplayList(nsD
   if (mIsBevelled) {
     DisplaySlash(aBuilder, this, mLineRect, mLineThickness, aLists);
   } else {
     DisplayBar(aBuilder, this, mLineRect, aLists);
   }
 }
 
 /* virtual */ nsresult
-nsMathMLmfracFrame::MeasureForWidth(nsRenderingContext& aRenderingContext,
+nsMathMLmfracFrame::MeasureForWidth(DrawTarget* aDrawTarget,
                                     nsHTMLReflowMetrics& aDesiredSize)
 {
-  return PlaceInternal(aRenderingContext,
-                       false,
-                       aDesiredSize,
-                       true);
+  return PlaceInternal(aDrawTarget, false, aDesiredSize, true);
 }
 
 nscoord
 nsMathMLmfracFrame::FixInterFrameSpacing(nsHTMLReflowMetrics& aDesiredSize)
 {
   nscoord gap = nsMathMLContainerFrame::FixInterFrameSpacing(aDesiredSize);
   if (!gap) return 0;
 
   mLineRect.MoveBy(gap, 0);
   return gap;
 }
 
 /* virtual */ nsresult
-nsMathMLmfracFrame::Place(nsRenderingContext& aRenderingContext,
+nsMathMLmfracFrame::Place(DrawTarget*          aDrawTarget,
                           bool                 aPlaceOrigin,
                           nsHTMLReflowMetrics& aDesiredSize)
 {
-  return PlaceInternal(aRenderingContext,
-                       aPlaceOrigin,
-                       aDesiredSize,
-                       false);
+  return PlaceInternal(aDrawTarget, aPlaceOrigin, aDesiredSize, false);
 }
 
 nsresult
-nsMathMLmfracFrame::PlaceInternal(nsRenderingContext& aRenderingContext,
+nsMathMLmfracFrame::PlaceInternal(DrawTarget*          aDrawTarget,
                                   bool                 aPlaceOrigin,
                                   nsHTMLReflowMetrics& aDesiredSize,
                                   bool                 aWidthOnly)
 {
   ////////////////////////////////////
   // Get the children's desired sizes
   nsBoundingMetrics bmNum, bmDen;
   nsHTMLReflowMetrics sizeNum(aDesiredSize.GetWritingMode());
@@ -210,17 +204,17 @@ nsMathMLmfracFrame::PlaceInternal(nsRend
   nsIFrame* frameNum = mFrames.FirstChild();
   if (frameNum) 
     frameDen = frameNum->GetNextSibling();
   if (!frameNum || !frameDen || frameDen->GetNextSibling()) {
     // report an error, encourage people to get their markups in order
     if (aPlaceOrigin) {
       ReportChildCountError();
     }
-    return ReflowError(aRenderingContext, aDesiredSize);
+    return ReflowError(aDrawTarget, aDesiredSize);
   }
   GetReflowAndBoundingMetricsFor(frameNum, sizeNum, bmNum);
   GetReflowAndBoundingMetricsFor(frameDen, sizeDen, bmDen);
 
   nsPresContext* presContext = PresContext();
   nscoord onePixel = nsPresContext::CSSPixelsToAppUnits(1);
 
   float fontSizeInflation = nsLayoutUtils::FontSizeInflationFor(this);
@@ -231,19 +225,19 @@ nsMathMLmfracFrame::PlaceInternal(nsRend
   nscoord defaultRuleThickness, axisHeight;
   nscoord oneDevPixel = fm->AppUnitsPerDevPixel();
   gfxFont* mathFont = fm->GetThebesFontGroup()->GetFirstMathFont();
   if (mathFont) {
     defaultRuleThickness =
       mathFont->GetMathConstant(gfxFontEntry::FractionRuleThickness,
                                 oneDevPixel);
   } else {
-    GetRuleThickness(aRenderingContext, fm, defaultRuleThickness);
+    GetRuleThickness(aDrawTarget, fm, defaultRuleThickness);
   }
-  GetAxisHeight(aRenderingContext, fm, axisHeight);
+  GetAxisHeight(aDrawTarget, fm, axisHeight);
 
   bool outermostEmbellished = false;
   if (mEmbellishData.coreFrame) {
     nsEmbellishData parentData;
     GetEmbellishDataFrom(GetParent(), parentData);
     outermostEmbellished = parentData.coreFrame != mEmbellishData.coreFrame;
   }
 
--- a/layout/mathml/nsMathMLmfracFrame.h
+++ b/layout/mathml/nsMathMLmfracFrame.h
@@ -53,21 +53,21 @@ class nsMathMLmfracFrame : public nsMath
 public:
   NS_DECL_FRAMEARENA_HELPERS
 
   friend nsIFrame* NS_NewMathMLmfracFrame(nsIPresShell* aPresShell, nsStyleContext* aContext);
 
   virtual eMathMLFrameType GetMathMLFrameType() override;
 
   virtual nsresult
-  MeasureForWidth(nsRenderingContext& aRenderingContext,
+  MeasureForWidth(DrawTarget* aDrawTarget,
                   nsHTMLReflowMetrics& aDesiredSize) override;
 
   virtual nsresult
-  Place(nsRenderingContext& aRenderingContext,
+  Place(DrawTarget*          aDrawTarget,
         bool                 aPlaceOrigin,
         nsHTMLReflowMetrics& aDesiredSize) override;
 
   virtual void BuildDisplayList(nsDisplayListBuilder*   aBuilder,
                                 const nsRect&           aDirtyRect,
                                 const nsDisplayListSet& aLists) override;
 
   NS_IMETHOD
@@ -87,18 +87,18 @@ public:
                     float            aFontSizeInflation);
 
   uint8_t
   ScriptIncrement(nsIFrame* aFrame) override;
 
 protected:
   explicit nsMathMLmfracFrame(nsStyleContext* aContext) : nsMathMLContainerFrame(aContext) {}
   virtual ~nsMathMLmfracFrame();
-  
-  nsresult PlaceInternal(nsRenderingContext& aRenderingContext,
+
+  nsresult PlaceInternal(DrawTarget*          aDrawTarget,
                          bool                 aPlaceOrigin,
                          nsHTMLReflowMetrics& aDesiredSize,
                          bool                 aWidthOnly);
 
   // Display a slash
   void DisplaySlash(nsDisplayListBuilder* aBuilder,
                     nsIFrame* aFrame, const nsRect& aRect,
                     nscoord aThickness,
--- a/layout/mathml/nsMathMLmmultiscriptsFrame.cpp
+++ b/layout/mathml/nsMathMLmmultiscriptsFrame.cpp
@@ -85,17 +85,17 @@ nsMathMLmmultiscriptsFrame::TransmitAuto
     PropagatePresentationDataFor(childFrame,
       NS_MATHML_COMPRESSED, NS_MATHML_COMPRESSED);
   }
 
   return NS_OK;
 }
 
 /* virtual */ nsresult
-nsMathMLmmultiscriptsFrame::Place(nsRenderingContext& aRenderingContext,
+nsMathMLmmultiscriptsFrame::Place(DrawTarget*          aDrawTarget,
                                   bool                 aPlaceOrigin,
                                   nsHTMLReflowMetrics& aDesiredSize)
 {
   nscoord subScriptShift = 0;
   nscoord supScriptShift = 0;
   float fontSizeInflation = nsLayoutUtils::FontSizeInflationFor(this);
 
   // subscriptshift
@@ -130,26 +130,26 @@ nsMathMLmmultiscriptsFrame::Place(nsRend
   //
   if (!mContent->IsMathMLElement(nsGkAtoms::msub_)) {
     mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::superscriptshift_, value);
     if (!value.IsEmpty()) {
       ParseNumericValue(value, &supScriptShift, 0, PresContext(),
                         mStyleContext, fontSizeInflation);
     }
   }
-  return PlaceMultiScript(PresContext(), aRenderingContext, aPlaceOrigin,
+  return PlaceMultiScript(PresContext(), aDrawTarget, aPlaceOrigin,
                           aDesiredSize, this, subScriptShift, supScriptShift,
                           fontSizeInflation);
 }
 
 // exported routine that both munderover and mmultiscripts share.
 // munderover uses this when movablelimits is set.
 nsresult
-nsMathMLmmultiscriptsFrame::PlaceMultiScript(nsPresContext*      aPresContext,
-                                        nsRenderingContext& aRenderingContext,
+nsMathMLmmultiscriptsFrame::PlaceMultiScript(nsPresContext*  aPresContext,
+                                        DrawTarget*          aDrawTarget,
                                         bool                 aPlaceOrigin,
                                         nsHTMLReflowMetrics& aDesiredSize,
                                         nsMathMLContainerFrame* aFrame,
                                         nscoord              aUserSubScriptShift,
                                         nscoord              aUserSupScriptShift,
                                         float                aFontSizeInflation)
 {
   nsIAtom* tag = aFrame->GetContent()->NodeInfo()->NameAtom();
@@ -175,17 +175,17 @@ nsMathMLmmultiscriptsFrame::PlaceMultiSc
 
   nsIFrame* baseFrame = aFrame->GetFirstPrincipalChild();
 
   if (!baseFrame) {
     if (tag == nsGkAtoms::mmultiscripts_)
       aFrame->ReportErrorToConsole("NoBase");
     else
       aFrame->ReportChildCountError();
-    return aFrame->ReflowError(aRenderingContext, aDesiredSize);
+    return aFrame->ReflowError(aDrawTarget, aDesiredSize);
   }
 
   // get x-height (an ex)
   const nsStyleFont* font = aFrame->StyleFont();
   RefPtr<nsFontMetrics> fm;
   nsLayoutUtils::GetFontMetricsForFrame(baseFrame, getter_AddRefs(fm),
                                         aFontSizeInflation);
 
@@ -324,44 +324,44 @@ nsMathMLmmultiscriptsFrame::PlaceMultiSc
 
   nsIFrame* childFrame = aFrame->GetFirstPrincipalChild();
   while (childFrame) {
     if (childFrame->GetContent()->IsMathMLElement(nsGkAtoms::mprescripts_)) {
       if (tag != nsGkAtoms::mmultiscripts_) {
         if (aPlaceOrigin) {
           aFrame->ReportInvalidChildError(nsGkAtoms::mprescripts_);
         }
-        return aFrame->ReflowError(aRenderingContext, aDesiredSize);
+        return aFrame->ReflowError(aDrawTarget, aDesiredSize);
       }
       if (prescriptsFrame) {
         // duplicate <mprescripts/> found
         // report an error, encourage people to get their markups in order
         if (aPlaceOrigin) {
           aFrame->ReportErrorToConsole("DuplicateMprescripts");
         }
-        return aFrame->ReflowError(aRenderingContext, aDesiredSize);
+        return aFrame->ReflowError(aDrawTarget, aDesiredSize);
       }
       if (!isSubScript) {
         if (aPlaceOrigin) {
           aFrame->ReportErrorToConsole("SubSupMismatch");
         }
-        return aFrame->ReflowError(aRenderingContext, aDesiredSize);
+        return aFrame->ReflowError(aDrawTarget, aDesiredSize);
       }
 
       prescriptsFrame = childFrame;
       firstPrescriptsPair = true;
     } else if (0 == count) {
       // base
 
       if (childFrame->GetContent()->IsMathMLElement(nsGkAtoms::none)) {
         if (tag == nsGkAtoms::mmultiscripts_) {
           if (aPlaceOrigin) {
             aFrame->ReportErrorToConsole("NoBase");
           }
-          return aFrame->ReflowError(aRenderingContext, aDesiredSize);
+          return aFrame->ReflowError(aDrawTarget, aDesiredSize);
         } else {
           //A different error message is triggered later for the other tags
           foundNoneTag = true;
         }
       }
       baseFrame = childFrame;
       GetReflowAndBoundingMetricsFor(baseFrame, baseSize, bmBase);
 
@@ -483,17 +483,17 @@ nsMathMLmmultiscriptsFrame::PlaceMultiSc
             tag == nsGkAtoms::msubsup_) {
           nscoord subSuperscriptGapMin;
           if (mathFont) {
             subSuperscriptGapMin =
               mathFont->GetMathConstant(gfxFontEntry::SubSuperscriptGapMin,
                                         oneDevPixel);
           } else {
             nscoord ruleSize;
-            GetRuleThickness(aRenderingContext, fm, ruleSize);
+            GetRuleThickness(aDrawTarget, fm, ruleSize);
             subSuperscriptGapMin = 4 * ruleSize;
           }
           nscoord gap =
             (trySupScriptShift - bmSupScript.descent) -
             (bmSubScript.ascent - trySubScriptShift);
           if (gap < subSuperscriptGapMin) {
             // adjust trySubScriptShift to get a gap of subSuperscriptGapMin
             trySubScriptShift += subSuperscriptGapMin - gap;
@@ -545,17 +545,17 @@ nsMathMLmmultiscriptsFrame::PlaceMultiSc
       } else if (foundNoneTag && tag != nsGkAtoms::mmultiscripts_) {
         aFrame->ReportInvalidChildError(nsGkAtoms::none);
       } else if (!baseFrame) {
         aFrame->ReportErrorToConsole("NoBase");
       } else {
         aFrame->ReportErrorToConsole("SubSupMismatch");
       }
     }
-    return aFrame->ReflowError(aRenderingContext, aDesiredSize);
+    return aFrame->ReflowError(aDrawTarget, aDesiredSize);
   }
 
   // we left out the width of prescripts, so ...
   boundingMetrics.rightBearing += prescriptsWidth;
   boundingMetrics.width += prescriptsWidth;
 
   // Zero out the shifts in where a frame isn't present to avoid the potential
   // for overflow.
--- a/layout/mathml/nsMathMLmmultiscriptsFrame.h
+++ b/layout/mathml/nsMathMLmmultiscriptsFrame.h
@@ -21,29 +21,29 @@ public:
   NS_DECL_FRAMEARENA_HELPERS
 
   friend nsIFrame* NS_NewMathMLmmultiscriptsFrame(nsIPresShell* aPresShell, nsStyleContext* aContext);
 
   NS_IMETHOD
   TransmitAutomaticData() override;
 
   virtual nsresult
-  Place(nsRenderingContext& aRenderingContext,
+  Place(DrawTarget*          aDrawTarget,
         bool                 aPlaceOrigin,
         nsHTMLReflowMetrics& aDesiredSize) override;
 
   static nsresult
-  PlaceMultiScript(nsPresContext*      aPresContext,
-                    nsRenderingContext& aRenderingContext,
-                    bool                 aPlaceOrigin,
-                    nsHTMLReflowMetrics& aDesiredSize,
-                    nsMathMLContainerFrame* aForFrame,
-                    nscoord              aUserSubScriptShift,
-                    nscoord              aUserSupScriptShift,
-                    float                aFontSizeInflation);
+  PlaceMultiScript(nsPresContext*          aPresContext,
+                   DrawTarget*             aDrawTarget,
+                   bool                    aPlaceOrigin,
+                   nsHTMLReflowMetrics&    aDesiredSize,
+                   nsMathMLContainerFrame* aForFrame,
+                   nscoord                 aUserSubScriptShift,
+                   nscoord                 aUserSupScriptShift,
+                   float                   aFontSizeInflation);
 
   uint8_t
   ScriptIncrement(nsIFrame* aFrame) override;
 
 protected:
   explicit nsMathMLmmultiscriptsFrame(nsStyleContext* aContext) : nsMathMLContainerFrame(aContext) {}
   virtual ~nsMathMLmmultiscriptsFrame();
   
--- a/layout/mathml/nsMathMLmoFrame.cpp
+++ b/layout/mathml/nsMathMLmoFrame.cpp
@@ -599,17 +599,17 @@ GetStretchHint(nsOperatorFlags aFlags, n
   }
   return stretchHint;
 }
 
 // NOTE: aDesiredStretchSize is an IN/OUT parameter
 //       On input  - it contains our current size
 //       On output - the same size or the new size that we want
 NS_IMETHODIMP
-nsMathMLmoFrame::Stretch(nsRenderingContext& aRenderingContext,
+nsMathMLmoFrame::Stretch(DrawTarget*          aDrawTarget,
                          nsStretchDirection   aStretchDirection,
                          nsBoundingMetrics&   aContainerSize,
                          nsHTMLReflowMetrics& aDesiredStretchSize)
 {
   if (NS_MATHML_STRETCH_WAS_DONE(mPresentationData.flags)) {
     NS_WARNING("it is wrong to fire stretch more than once on a frame");
     return NS_OK;
   }
@@ -618,17 +618,17 @@ nsMathMLmoFrame::Stretch(nsRenderingCont
   nsIFrame* firstChild = mFrames.FirstChild();
 
   // get the axis height;
   float fontSizeInflation = nsLayoutUtils::FontSizeInflationFor(this);
   RefPtr<nsFontMetrics> fm;
   nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
                                         fontSizeInflation);
   nscoord axisHeight, height;
-  GetAxisHeight(aRenderingContext, fm, axisHeight);
+  GetAxisHeight(aDrawTarget, fm, axisHeight);
 
   // get the leading to be left at the top and the bottom of the stretched char
   // this seems more reliable than using fm->GetLeading() on suspicious fonts
   nscoord em;
   GetEmHeight(fm, em);
   nscoord leading = NSToCoordRound(0.2f * em);
 
   // Operators that are stretchy, or those that are to be centered
@@ -743,32 +743,32 @@ nsMathMLmoFrame::Stretch(nsRenderingCont
           height = container.ascent + container.descent;
           container.descent = aContainerSize.descent;
           container.ascent = height - container.descent;
         }
       }
     }
 
     // let the MathMLChar stretch itself...
-    nsresult res = mMathMLChar.Stretch(PresContext(), aRenderingContext,
+    nsresult res = mMathMLChar.Stretch(PresContext(), aDrawTarget,
                                        fontSizeInflation,
                                        aStretchDirection, container, charSize,
                                        stretchHint,
                                        StyleVisibility()->mDirection);
     if (NS_FAILED(res)) {
       // gracefully handle cases where stretching the char failed (i.e., GetBoundingMetrics failed)
       // clear our 'form' to behave as if the operator wasn't in the dictionary
       mFlags &= ~NS_MATHML_OPERATOR_FORM;
       useMathMLChar = false;
     }
   }
 
   // Place our children using the default method
   // This will allow our child text frame to get its DidReflow()
-  nsresult rv = Place(aRenderingContext, true, aDesiredStretchSize);
+  nsresult rv = Place(aDrawTarget, true, aDesiredStretchSize);
   if (NS_MATHML_HAS_ERROR(mPresentationData.flags) || NS_FAILED(rv)) {
     // Make sure the child frames get their DidReflow() calls.
     DidReflowChildren(mFrames.FirstChild());
   }
 
   if (useMathMLChar) {
     // update our bounding metrics... it becomes that of our MathML char
     mBoundingMetrics = charSize;
@@ -954,22 +954,21 @@ nsMathMLmoFrame::Reflow(nsPresContext*  
   // it is safer to just process the whole lot here
   ProcessOperatorData();
 
   nsMathMLTokenFrame::Reflow(aPresContext, aDesiredSize,
                              aReflowState, aStatus);
 }
 
 nsresult
-nsMathMLmoFrame::Place(nsRenderingContext&  aRenderingContext,
+nsMathMLmoFrame::Place(DrawTarget*          aDrawTarget,
                        bool                 aPlaceOrigin,
                        nsHTMLReflowMetrics& aDesiredSize)
 {
-  nsresult rv = nsMathMLTokenFrame::Place(aRenderingContext, aPlaceOrigin,
-                                          aDesiredSize);
+  nsresult rv = nsMathMLTokenFrame::Place(aDrawTarget, aPlaceOrigin, aDesiredSize);
 
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   /* Special behaviour for largeops.
      In MathML "stretchy" and displaystyle "largeop" are different notions,
      even if we use the same technique to draw them (picking size variants).
@@ -980,21 +979,21 @@ nsMathMLmoFrame::Place(nsRenderingContex
      This is a preliminary stretch - exact sizing/placement is handled by the
      Stretch() method.
   */
 
   if (!aPlaceOrigin &&
       StyleFont()->mMathDisplay == NS_MATHML_DISPLAYSTYLE_BLOCK &&
       NS_MATHML_OPERATOR_IS_LARGEOP(mFlags) && UseMathMLChar()) {
     nsBoundingMetrics newMetrics;
-    rv = mMathMLChar.Stretch(PresContext(), aRenderingContext,
-                                      nsLayoutUtils::FontSizeInflationFor(this),
-                                      NS_STRETCH_DIRECTION_VERTICAL,
-                                      aDesiredSize.mBoundingMetrics, newMetrics,
-                                      NS_STRETCH_LARGEOP, StyleVisibility()->mDirection);
+    rv = mMathMLChar.Stretch(PresContext(), aDrawTarget,
+                             nsLayoutUtils::FontSizeInflationFor(this),
+                             NS_STRETCH_DIRECTION_VERTICAL,
+                             aDesiredSize.mBoundingMetrics, newMetrics,
+                             NS_STRETCH_LARGEOP, StyleVisibility()->mDirection);
 
     if (NS_FAILED(rv)) {
       // Just use the initial size
       return NS_OK;
     }
 
     aDesiredSize.mBoundingMetrics = newMetrics;
      /* Treat the ascent/descent values calculated in the TokenFrame place
@@ -1041,17 +1040,17 @@ nsMathMLmoFrame::MarkIntrinsicISizesDirt
 nsMathMLmoFrame::GetIntrinsicISizeMetrics(nsRenderingContext* aRenderingContext,
                                           nsHTMLReflowMetrics& aDesiredSize)
 {
   ProcessOperatorData();
   if (UseMathMLChar()) {
     uint32_t stretchHint = GetStretchHint(mFlags, mPresentationData, true,
                                           StyleFont());
     aDesiredSize.Width() = mMathMLChar.
-      GetMaxWidth(PresContext(), *aRenderingContext,
+      GetMaxWidth(PresContext(), aRenderingContext->GetDrawTarget(),
                   nsLayoutUtils::FontSizeInflationFor(this),
                   stretchHint);
   }
   else {
     nsMathMLTokenFrame::GetIntrinsicISizeMetrics(aRenderingContext,
                                                  aDesiredSize);
   }
 
--- a/layout/mathml/nsMathMLmoFrame.h
+++ b/layout/mathml/nsMathMLmoFrame.h
@@ -44,17 +44,17 @@ public:
 
   virtual void
   Reflow(nsPresContext*          aPresContext,
          nsHTMLReflowMetrics&     aDesiredSize,
          const nsHTMLReflowState& aReflowState,
          nsReflowStatus&          aStatus) override;
 
   virtual nsresult
-  Place(nsRenderingContext& aRenderingContext,
+  Place(DrawTarget*          aDrawTarget,
         bool                 aPlaceOrigin,
         nsHTMLReflowMetrics& aDesiredSize) override;
 
   virtual void MarkIntrinsicISizesDirty() override;
 
   virtual void
   GetIntrinsicISizeMetrics(nsRenderingContext* aRenderingContext,
                            nsHTMLReflowMetrics& aDesiredSize) override;
@@ -62,17 +62,17 @@ public:
   virtual nsresult
   AttributeChanged(int32_t         aNameSpaceID,
                    nsIAtom*        aAttribute,
                    int32_t         aModType) override;
 
   // This method is called by the parent frame to ask <mo> 
   // to stretch itself.
   NS_IMETHOD
-  Stretch(nsRenderingContext& aRenderingContext,
+  Stretch(DrawTarget*          aDrawTarget,
           nsStretchDirection   aStretchDirection,
           nsBoundingMetrics&   aContainerSize,
           nsHTMLReflowMetrics& aDesiredStretchSize) override;
 
   virtual nsresult
   ChildListChanged(int32_t aModType) override
   {
     ProcessTextData();
--- a/layout/mathml/nsMathMLmpaddedFrame.cpp
+++ b/layout/mathml/nsMathMLmpaddedFrame.cpp
@@ -314,22 +314,22 @@ nsMathMLmpaddedFrame::Reflow(nsPresConte
   ///////////////
   // Let the base class format our content like an inferred mrow
   nsMathMLContainerFrame::Reflow(aPresContext, aDesiredSize,
                                  aReflowState, aStatus);
   //NS_ASSERTION(NS_FRAME_IS_COMPLETE(aStatus), "bad status");
 }
 
 /* virtual */ nsresult
-nsMathMLmpaddedFrame::Place(nsRenderingContext& aRenderingContext,
+nsMathMLmpaddedFrame::Place(DrawTarget*          aDrawTarget,
                             bool                 aPlaceOrigin,
                             nsHTMLReflowMetrics& aDesiredSize)
 {
   nsresult rv =
-    nsMathMLContainerFrame::Place(aRenderingContext, false, aDesiredSize);
+    nsMathMLContainerFrame::Place(aDrawTarget, false, aDesiredSize);
   if (NS_MATHML_HAS_ERROR(mPresentationData.flags) || NS_FAILED(rv)) {
     DidReflowChildren(GetFirstPrincipalChild());
     return rv;
   }
 
   nscoord height = aDesiredSize.BlockStartAscent();
   nscoord depth  = aDesiredSize.Height() - aDesiredSize.BlockStartAscent();
   // The REC says:
@@ -436,14 +436,14 @@ nsMathMLmpaddedFrame::Place(nsRenderingC
     // Finish reflowing child frames, positioning their origins.
     PositionRowChildFrames(dx, aDesiredSize.BlockStartAscent() - voffset);
   }
 
   return NS_OK;
 }
 
 /* virtual */ nsresult
-nsMathMLmpaddedFrame::MeasureForWidth(nsRenderingContext& aRenderingContext,
+nsMathMLmpaddedFrame::MeasureForWidth(DrawTarget* aDrawTarget,
                                       nsHTMLReflowMetrics& aDesiredSize)
 {
   ProcessAttributes();
-  return Place(aRenderingContext, false, aDesiredSize);
+  return Place(aDrawTarget, false, aDesiredSize);
 }
--- a/layout/mathml/nsMathMLmpaddedFrame.h
+++ b/layout/mathml/nsMathMLmpaddedFrame.h
@@ -29,32 +29,32 @@ public:
 
   virtual void
   Reflow(nsPresContext*          aPresContext,
          nsHTMLReflowMetrics&     aDesiredSize,
          const nsHTMLReflowState& aReflowState,
          nsReflowStatus&          aStatus) override;
   
   virtual nsresult
-  Place(nsRenderingContext& aRenderingContext,
+  Place(DrawTarget*          aDrawTarget,
         bool                 aPlaceOrigin,
         nsHTMLReflowMetrics& aDesiredSize) override;
 
   bool
   IsMrowLike() override {
     return mFrames.FirstChild() != mFrames.LastChild() ||
            !mFrames.FirstChild();
   }
 
 protected:
   explicit nsMathMLmpaddedFrame(nsStyleContext* aContext) : nsMathMLContainerFrame(aContext) {}
   virtual ~nsMathMLmpaddedFrame();
-  
+
   virtual nsresult
-  MeasureForWidth(nsRenderingContext& aRenderingContext,
+  MeasureForWidth(DrawTarget* aDrawTarget,
                   nsHTMLReflowMetrics& aDesiredSize) override;
 
 private:
   nsCSSValue mWidth;
   nsCSSValue mHeight;
   nsCSSValue mDepth;
   nsCSSValue mLeadingSpace;
   nsCSSValue mVerticalOffset;
--- a/layout/mathml/nsMathMLmrootFrame.cpp
+++ b/layout/mathml/nsMathMLmrootFrame.cpp
@@ -167,17 +167,17 @@ nsMathMLmrootFrame::Reflow(nsPresContext
   MarkInReflow();
   nsReflowStatus childStatus;
 
   mPresentationData.flags &= ~NS_MATHML_ERROR;
   aDesiredSize.ClearSize();
   aDesiredSize.SetBlockStartAscent(0);
 
   nsBoundingMetrics bmSqr, bmBase, bmIndex;
-  nsRenderingContext& renderingContext = *aReflowState.rendContext;
+  DrawTarget* drawTarget = aReflowState.rendContext->GetDrawTarget();
 
   //////////////////
   // Reflow Children
 
   int32_t count = 0;
   nsIFrame* baseFrame = nullptr;
   nsIFrame* indexFrame = nullptr;
   nsHTMLReflowMetrics baseSize(aReflowState);
@@ -209,17 +209,17 @@ nsMathMLmrootFrame::Reflow(nsPresContext
       bmIndex = childDesiredSize.mBoundingMetrics;
     }
     count++;
     childFrame = childFrame->GetNextSibling();
   }
   if (2 != count) {
     // report an error, encourage people to get their markups in order
     ReportChildCountError();
-    ReflowError(renderingContext, aDesiredSize);
+    ReflowError(drawTarget, aDesiredSize);
     aStatus = NS_FRAME_COMPLETE;
     NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aDesiredSize);
     // Call DidReflow() for the child frames we successfully did reflow.
     DidReflowChildren(mFrames.FirstChild(), childFrame);
     return;
   }
 
   ////////////
@@ -233,17 +233,17 @@ nsMathMLmrootFrame::Reflow(nsPresContext
   nscoord ruleThickness, leading, psi;
   GetRadicalParameters(fm, StyleFont()->mMathDisplay ==
                        NS_MATHML_DISPLAYSTYLE_BLOCK,
                        ruleThickness, leading, psi);
 
   // built-in: adjust clearance psi to emulate \mathstrut using '1' (TexBook, p.131)
   char16_t one = '1';
   nsBoundingMetrics bmOne =
-    nsLayoutUtils::AppUnitBoundsOfString(&one, 1, *fm, renderingContext);
+    nsLayoutUtils::AppUnitBoundsOfString(&one, 1, *fm, drawTarget);
   if (bmOne.ascent > bmBase.ascent)
     psi += bmOne.ascent - bmBase.ascent;
 
   // make sure that the rule appears on on screen
   nscoord onePixel = nsPresContext::CSSPixelsToAppUnits(1);
   if (ruleThickness < onePixel) {
     ruleThickness = onePixel;
   }
@@ -256,17 +256,17 @@ nsMathMLmrootFrame::Reflow(nsPresContext
 
   // Stretch the radical symbol to the appropriate height if it is not big enough.
   nsBoundingMetrics contSize = bmBase;
   contSize.descent = bmBase.ascent + bmBase.descent + psi;
   contSize.ascent = ruleThickness;
 
   // height(radical) should be >= height(base) + psi + ruleThickness
   nsBoundingMetrics radicalSize;
-  mSqrChar.Stretch(aPresContext, renderingContext,
+  mSqrChar.Stretch(aPresContext, drawTarget,
                    fontSizeInflation,
                    NS_STRETCH_DIRECTION_VERTICAL, 
                    contSize, radicalSize,
                    NS_STRETCH_LARGER,
                    StyleVisibility()->mDirection);
   // radicalSize have changed at this point, and should match with
   // the bounding metrics of the char
   mSqrChar.GetBoundingMetrics(bmSqr);
@@ -361,28 +361,29 @@ nsMathMLmrootFrame::Reflow(nsPresContext
 /* virtual */ void
 nsMathMLmrootFrame::GetIntrinsicISizeMetrics(nsRenderingContext* aRenderingContext, nsHTMLReflowMetrics& aDesiredSize)
 {
   nsIFrame* baseFrame = mFrames.FirstChild();
   nsIFrame* indexFrame = nullptr;
   if (baseFrame)
     indexFrame = baseFrame->GetNextSibling();
   if (!indexFrame || indexFrame->GetNextSibling()) {
-    ReflowError(*aRenderingContext, aDesiredSize);
+    ReflowError(aRenderingContext->GetDrawTarget(), aDesiredSize);
     return;
   }
 
   float fontSizeInflation = nsLayoutUtils::FontSizeInflationFor(this);
   nscoord baseWidth =
     nsLayoutUtils::IntrinsicForContainer(aRenderingContext, baseFrame,
                                          nsLayoutUtils::PREF_ISIZE);
   nscoord indexWidth =
     nsLayoutUtils::IntrinsicForContainer(aRenderingContext, indexFrame,
                                          nsLayoutUtils::PREF_ISIZE);
-  nscoord sqrWidth = mSqrChar.GetMaxWidth(PresContext(), *aRenderingContext,
+  nscoord sqrWidth = mSqrChar.GetMaxWidth(PresContext(),
+                                          aRenderingContext->GetDrawTarget(),
                                           fontSizeInflation);
 
   nscoord dxSqr;
   RefPtr<nsFontMetrics> fm;
   nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
                                         fontSizeInflation);
   GetRadicalXOffsets(indexWidth, sqrWidth, fm, nullptr, &dxSqr);
 
--- a/layout/mathml/nsMathMLmspaceFrame.cpp
+++ b/layout/mathml/nsMathMLmspaceFrame.cpp
@@ -115,17 +115,17 @@ nsMathMLmspaceFrame::Reflow(nsPresContex
   // Also return our bounding metrics
   aDesiredSize.mBoundingMetrics = mBoundingMetrics;
 
   aStatus = NS_FRAME_COMPLETE;
   NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aDesiredSize);
 }
 
 /* virtual */ nsresult
-nsMathMLmspaceFrame::MeasureForWidth(nsRenderingContext& aRenderingContext,
+nsMathMLmspaceFrame::MeasureForWidth(DrawTarget* aDrawTarget,
                                      nsHTMLReflowMetrics& aDesiredSize)
 {
   ProcessAttributes(PresContext());
   mBoundingMetrics = nsBoundingMetrics();
   mBoundingMetrics.width = mWidth;
   aDesiredSize.Width() = std::max(0, mBoundingMetrics.width);
   aDesiredSize.mBoundingMetrics = mBoundingMetrics;
   return NS_OK;
--- a/layout/mathml/nsMathMLmspaceFrame.h
+++ b/layout/mathml/nsMathMLmspaceFrame.h
@@ -35,17 +35,17 @@ public:
          const nsHTMLReflowState& aReflowState,
          nsReflowStatus&          aStatus) override;
   
 protected:
   explicit nsMathMLmspaceFrame(nsStyleContext* aContext) : nsMathMLContainerFrame(aContext) {}
   virtual ~nsMathMLmspaceFrame();
 
   virtual nsresult
-  MeasureForWidth(nsRenderingContext& aRenderingContext,
+  MeasureForWidth(DrawTarget* aDrawTarget,
                   nsHTMLReflowMetrics& aDesiredSize) override;
 
 private:
   nscoord mWidth;
   nscoord mHeight;
   nscoord mDepth;
 
   // helper method to initialize our member data
--- a/layout/mathml/nsMathMLmtableFrame.cpp
+++ b/layout/mathml/nsMathMLmtableFrame.cpp
@@ -883,17 +883,17 @@ nsMathMLmtableOuterFrame::Reflow(nsPresC
     case eAlign_axis:
     default: {
       // XXX should instead use style data from the row of reference here ?
       RefPtr<nsFontMetrics> fm;
       nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
                                             nsLayoutUtils::
                                             FontSizeInflationFor(this));
       nscoord axisHeight;
-      GetAxisHeight(*aReflowState.rendContext, fm, axisHeight);
+      GetAxisHeight(aReflowState.rendContext->GetDrawTarget(), fm, axisHeight);
       if (rowFrame) {
         // anchor the table on the axis of the row of reference
         // XXX fallback to baseline because it is a hard problem
         // XXX need to fetch the axis of the row; would need rowalign=axis to work better
         nscoord rowAscent = ((nsTableRowFrame*)rowFrame)->GetMaxCellAscent();
         if (rowAscent) { // the row has at least one cell with 'vertical-align: baseline'
           aDesiredSize.SetBlockStartAscent(dy + rowAscent);
           break;
--- a/layout/mathml/nsMathMLmunderoverFrame.cpp
+++ b/layout/mathml/nsMathMLmunderoverFrame.cpp
@@ -296,43 +296,43 @@ i.e.,:
   // place like subscript-superscript pair
  }
  else {
   // place like underscript-overscript pair
  }
 */
 
 /* virtual */ nsresult
-nsMathMLmunderoverFrame::Place(nsRenderingContext& aRenderingContext,
+nsMathMLmunderoverFrame::Place(DrawTarget*          aDrawTarget,
                                bool                 aPlaceOrigin,
                                nsHTMLReflowMetrics& aDesiredSize)
 {
   float fontSizeInflation = nsLayoutUtils::FontSizeInflationFor(this);
   if (NS_MATHML_EMBELLISH_IS_MOVABLELIMITS(mEmbellishData.flags) &&
       StyleFont()->mMathDisplay == NS_MATHML_DISPLAYSTYLE_INLINE) {
     //place like sub sup or subsup
     if (mContent->IsMathMLElement(nsGkAtoms::munderover_)) {
       return nsMathMLmmultiscriptsFrame::PlaceMultiScript(PresContext(),
-                                                          aRenderingContext,
+                                                          aDrawTarget,
                                                           aPlaceOrigin,
                                                           aDesiredSize,
                                                           this, 0, 0,
                                                           fontSizeInflation);
     } else if (mContent->IsMathMLElement( nsGkAtoms::munder_)) {
       return nsMathMLmmultiscriptsFrame::PlaceMultiScript(PresContext(),
-                                                          aRenderingContext,
+                                                          aDrawTarget,
                                                           aPlaceOrigin,
                                                           aDesiredSize,
                                                           this, 0, 0,
                                                           fontSizeInflation);
     } else {
       NS_ASSERTION(mContent->IsMathMLElement(nsGkAtoms::mover_),
                    "mContent->NodeInfo()->NameAtom() not recognized");
       return nsMathMLmmultiscriptsFrame::PlaceMultiScript(PresContext(),
-                                                          aRenderingContext,
+                                                          aDrawTarget,
                                                           aPlaceOrigin,
                                                           aDesiredSize,
                                                           this, 0, 0,
                                                           fontSizeInflation);
     }
     
   }
 
@@ -377,18 +377,18 @@ nsMathMLmunderoverFrame::Place(nsRenderi
     if (!baseFrame || !underFrame || !overFrame || overFrame->GetNextSibling()) {
       // report an error, encourage people to get their markups in order
       haveError = true;
     }
   }
   if (haveError) {
     if (aPlaceOrigin) {
       ReportChildCountError();
-    } 
-    return ReflowError(aRenderingContext, aDesiredSize);
+    }
+    return ReflowError(aDrawTarget, aDesiredSize);
   }
   GetReflowAndBoundingMetricsFor(baseFrame, baseSize, bmBase);
   if (underFrame) {
     GetReflowAndBoundingMetricsFor(underFrame, underSize, bmUnder);
   }
   if (overFrame) {
     GetReflowAndBoundingMetricsFor(overFrame, overSize, bmOver);
   }
@@ -402,17 +402,17 @@ nsMathMLmunderoverFrame::Place(nsRenderi
   nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
                                         fontSizeInflation);
 
   nscoord xHeight = fm->XHeight();
   nscoord oneDevPixel = fm->AppUnitsPerDevPixel();
   gfxFont* mathFont = fm->GetThebesFontGroup()->GetFirstMathFont();
 
   nscoord ruleThickness;
-  GetRuleThickness (aRenderingContext, fm, ruleThickness);
+  GetRuleThickness (aDrawTarget, fm, ruleThickness);
 
   nscoord correction = 0;
   GetItalicCorrection (bmBase, correction);
 
   // there are 2 different types of placement depending on 
   // whether we want an accented under or not
 
   nscoord underDelta1 = 0; // gap between base and underscript
--- a/layout/mathml/nsMathMLmunderoverFrame.h
+++ b/layout/mathml/nsMathMLmunderoverFrame.h
@@ -15,17 +15,17 @@
 
 class nsMathMLmunderoverFrame : public nsMathMLContainerFrame {
 public:
   NS_DECL_FRAMEARENA_HELPERS
 
   friend nsIFrame* NS_NewMathMLmunderoverFrame(nsIPresShell* aPresShell, nsStyleContext* aContext);
 
   virtual nsresult
-  Place(nsRenderingContext& aRenderingContext,
+  Place(DrawTarget*          aDrawTarget,
         bool                 aPlaceOrigin,
         nsHTMLReflowMetrics& aDesiredSize) override;
 
   NS_IMETHOD
   InheritAutomaticData(nsIFrame* aParent) override;
 
   NS_IMETHOD
   TransmitAutomaticData() override;
--- a/layout/xul/nsTextBoxFrame.cpp
+++ b/layout/xul/nsTextBoxFrame.cpp
@@ -513,18 +513,19 @@ nsTextBoxFrame::DrawText(nsRenderingCont
                           ascentPixel, ascentPixel,
                           NS_STYLE_TEXT_DECORATION_LINE_OVERLINE, overStyle,
                           vertical);
       }
     }
 
     nsRenderingContext refContext(
         PresContext()->PresShell()->CreateReferenceRenderingContext());
+    DrawTarget* refDrawTarget = refContext.GetDrawTarget();
 
-    CalculateUnderline(refContext, *fontMet);
+    CalculateUnderline(refDrawTarget, *fontMet);
 
     nscolor c = aOverrideColor ? *aOverrideColor : StyleColor()->mColor;
     ColorPattern color(ToDeviceColor(c));
     aRenderingContext.ThebesContext()->SetColor(Color::FromABGR(c));
 
     nsresult rv = NS_ERROR_FAILURE;
 
     if (mState & NS_FRAME_IS_BIDI) {
@@ -532,50 +533,50 @@ nsTextBoxFrame::DrawText(nsRenderingCont
       nsBidiLevel level = nsBidiPresUtils::BidiLevelFromStyle(StyleContext());
       if (mAccessKeyInfo && mAccessKeyInfo->mAccesskeyIndex != kNotFound) {
           // We let the RenderText function calculate the mnemonic's
           // underline position for us.
           nsBidiPositionResolve posResolve;
           posResolve.logicalIndex = mAccessKeyInfo->mAccesskeyIndex;
           rv = nsBidiPresUtils::RenderText(mCroppedTitle.get(), mCroppedTitle.Length(), level,
                                            presContext, aRenderingContext,
-                                           refContext, *fontMet,
+                                           refDrawTarget, *fontMet,
                                            baselinePt.x, baselinePt.y,
                                            &posResolve,
                                            1);
           mAccessKeyInfo->mBeforeWidth = posResolve.visualLeftTwips;
           mAccessKeyInfo->mAccessWidth = posResolve.visualWidth;
       }
       else
       {
           rv = nsBidiPresUtils::RenderText(mCroppedTitle.get(), mCroppedTitle.Length(), level,
                                            presContext, aRenderingContext,
-                                           refContext, *fontMet,
+                                           refDrawTarget, *fontMet,
                                            baselinePt.x, baselinePt.y);
       }
     }
     if (NS_FAILED(rv)) {
        fontMet->SetTextRunRTL(false);
 
        if (mAccessKeyInfo && mAccessKeyInfo->mAccesskeyIndex != kNotFound) {
            // In the simple (non-BiDi) case, we calculate the mnemonic's
            // underline position by getting the text metric.
            // XXX are attribute values always two byte?
            if (mAccessKeyInfo->mAccesskeyIndex > 0)
                mAccessKeyInfo->mBeforeWidth = nsLayoutUtils::
                    AppUnitWidthOfString(mCroppedTitle.get(),
                                         mAccessKeyInfo->mAccesskeyIndex,
-                                        *fontMet, refContext);
+                                        *fontMet, refDrawTarget);
            else
                mAccessKeyInfo->mBeforeWidth = 0;
        }
 
        fontMet->DrawString(mCroppedTitle.get(), mCroppedTitle.Length(),
                            baselinePt.x, baselinePt.y, &aRenderingContext,
-                           &refContext);
+                           refDrawTarget);
     }
 
     if (mAccessKeyInfo && mAccessKeyInfo->mAccesskeyIndex != kNotFound) {
       nsRect r(aTextRect.x + mAccessKeyInfo->mBeforeWidth,
                aTextRect.y + mAccessKeyInfo->mAccessOffset,
                mAccessKeyInfo->mAccessWidth,
                mAccessKeyInfo->mAccessUnderlineSize);
       Rect devPxRect =
@@ -594,39 +595,41 @@ nsTextBoxFrame::DrawText(nsRenderingCont
                                           strikeColor,
                         pt, xInFrame, Size(width, sizePixel), ascentPixel,
                         offsetPixel, NS_STYLE_TEXT_DECORATION_LINE_LINE_THROUGH,
                         strikeStyle, vertical);
     }
 }
 
 void
-nsTextBoxFrame::CalculateUnderline(nsRenderingContext& aRenderingContext,
+nsTextBoxFrame::CalculateUnderline(DrawTarget* aDrawTarget,
                                    nsFontMetrics& aFontMetrics)
 {
     if (mAccessKeyInfo && mAccessKeyInfo->mAccesskeyIndex != kNotFound) {
          // Calculate all fields of mAccessKeyInfo which
          // are the same for both BiDi and non-BiDi frames.
          const char16_t *titleString = mCroppedTitle.get();
          aFontMetrics.SetTextRunRTL(false);
          mAccessKeyInfo->mAccessWidth = nsLayoutUtils::
              AppUnitWidthOfString(titleString[mAccessKeyInfo->mAccesskeyIndex],
-                                  aFontMetrics, aRenderingContext);
+                                  aFontMetrics, aDrawTarget);
 
          nscoord offset, baseline;
          aFontMetrics.GetUnderline(offset, mAccessKeyInfo->mAccessUnderlineSize);
          baseline = aFontMetrics.MaxAscent();
          mAccessKeyInfo->mAccessOffset = baseline - offset;
     }
 }
 
 nscoord
 nsTextBoxFrame::CalculateTitleForWidth(nsRenderingContext& aRenderingContext,
                                        nscoord              aWidth)
 {
+    DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
+
     if (mTitle.IsEmpty()) {
         mCroppedTitle.Truncate();
         return 0;
     }
 
     RefPtr<nsFontMetrics> fm;
     nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm));
 
@@ -646,17 +649,17 @@ nsTextBoxFrame::CalculateTitleForWidth(n
     const nsDependentString& kEllipsis = nsContentUtils::GetLocalizedEllipsis();
     // start with an ellipsis
     mCroppedTitle.Assign(kEllipsis);
 
     // see if the width is even smaller than the ellipsis
     // if so, clear the text (XXX set as many '.' as we can?).
     fm->SetTextRunRTL(false);
     titleWidth = nsLayoutUtils::AppUnitWidthOfString(kEllipsis, *fm,
-                                                     aRenderingContext);
+                                                     drawTarget);
 
     if (titleWidth > aWidth) {
         mCroppedTitle.SetLength(0);
         return 0;
     }
 
     // if the ellipsis fits perfectly, no use in trying to insert
     if (titleWidth == aWidth)
@@ -675,17 +678,17 @@ nsTextBoxFrame::CalculateTitleForWidth(n
             nscoord cwidth;
             nscoord twidth = 0;
             int length = mTitle.Length();
             int i;
             for (i = 0; i < length; ++i) {
                 char16_t ch = mTitle.CharAt(i);
                 // still in LTR mode
                 cwidth = nsLayoutUtils::AppUnitWidthOfString(ch, *fm,
-                                                             aRenderingContext);
+                                                             drawTarget);
                 if (twidth + cwidth > aWidth)
                     break;
 
                 twidth += cwidth;
                 if (UCS2_CHAR_IS_BIDI(ch) ) {
                   mState |= NS_FRAME_IS_BIDI;
                 }
             }
@@ -704,17 +707,17 @@ nsTextBoxFrame::CalculateTitleForWidth(n
         {
             nscoord cwidth;
             nscoord twidth = 0;
             int length = mTitle.Length();
             int i;
             for (i=length-1; i >= 0; --i) {
                 char16_t ch = mTitle.CharAt(i);
                 cwidth = nsLayoutUtils::AppUnitWidthOfString(ch, *fm,
-                                                             aRenderingContext);
+                                                             drawTarget);
                 if (twidth + cwidth > aWidth)
                     break;
 
                 twidth += cwidth;
                 if (UCS2_CHAR_IS_BIDI(ch) ) {
                   mState |= NS_FRAME_IS_BIDI;
                 }
             }
@@ -747,33 +750,33 @@ nsTextBoxFrame::CalculateTitleForWidth(n
             nsAutoString leftString, rightString;
 
             rightPos = mTitle.Length() - 1;
             fm->SetTextRunRTL(false);
             for (leftPos = 0; leftPos <= rightPos;) {
                 // look at the next character on the left end
                 ch = mTitle.CharAt(leftPos);
                 charWidth = nsLayoutUtils::AppUnitWidthOfString(ch, *fm,
-                                                                aRenderingContext);
+                                                                drawTarget);
                 totalWidth += charWidth;
                 if (totalWidth > aWidth)
                     // greater than the allowable width
                     break;
                 leftString.Insert(ch, leftString.Length());
 
                 if (UCS2_CHAR_IS_BIDI(ch))
                     mState |= NS_FRAME_IS_BIDI;
 
                 // look at the next character on the right end
                 if (rightPos > leftPos) {
                     // haven't looked at this character yet
                     ch = mTitle.CharAt(rightPos);
                     charWidth =
                         nsLayoutUtils::AppUnitWidthOfString(ch, *fm,
-                                                            aRenderingContext);
+                                                            drawTarget);
                     totalWidth += charWidth;
                     if (totalWidth > aWidth)
                         // greater than the allowable width
                         break;
                     rightString.Insert(ch, 0);
 
                     if (UCS2_CHAR_IS_BIDI(ch))
                         mState |= NS_FRAME_IS_BIDI;
@@ -957,17 +960,17 @@ nsTextBoxFrame::DoLayout(nsBoxLayoutStat
     nsRect scrollBounds(nsPoint(0, 0), GetSize());
     nsRect textRect = mTextDrawRect;
     
     RefPtr<nsFontMetrics> fontMet;
     nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fontMet));
     nsBoundingMetrics metrics = 
       fontMet->GetInkBoundsForVisualOverflow(mCroppedTitle.get(),
                                              mCroppedTitle.Length(),
-                                             aBoxLayoutState.GetRenderingContext());
+                                             aBoxLayoutState.GetRenderingContext()->GetDrawTarget());
 
     WritingMode wm = GetWritingMode();
     LogicalRect tr(wm, textRect, GetSize());
 
     tr.IStart(wm) -= metrics.leftBearing;
     tr.ISize(wm) = metrics.width;
     // In DrawText() we always draw with the baseline at MaxAscent() (relative to mTextDrawRect), 
     tr.BStart(wm) += fontMet->MaxAscent() - metrics.ascent;
--- a/layout/xul/nsTextBoxFrame.h
+++ b/layout/xul/nsTextBoxFrame.h
@@ -80,18 +80,17 @@ protected:
   // account text-transform.
   void RecomputeTitle();
 
   // REVIEW: SORRY! Couldn't resist devirtualizing these
   void LayoutTitle(nsPresContext*      aPresContext,
                    nsRenderingContext& aRenderingContext,
                    const nsRect&        aRect);
 
-  void CalculateUnderline(nsRenderingContext& aRenderingContext,
-                          nsFontMetrics& aFontMetrics);
+  void CalculateUnderline(DrawTarget* aDrawTarget, nsFontMetrics& aFontMetrics);
 
   void CalcTextSize(nsBoxLayoutState& aBoxLayoutState);
 
   void CalcDrawRect(nsRenderingContext &aRenderingContext);
 
   explicit nsTextBoxFrame(nsStyleContext* aContext);
 
   nscoord CalculateTitleForWidth(nsRenderingContext& aRenderingContext,
--- a/layout/xul/tree/nsTreeBodyFrame.cpp
+++ b/layout/xul/tree/nsTreeBodyFrame.cpp
@@ -1313,20 +1313,22 @@ void
 nsTreeBodyFrame::AdjustForCellText(nsAutoString& aText,
                                    int32_t aRowIndex,  nsTreeColumn* aColumn,
                                    nsRenderingContext& aRenderingContext,
                                    nsFontMetrics& aFontMetrics,
                                    nsRect& aTextRect)
 {
   NS_PRECONDITION(aColumn && aColumn->GetFrame(), "invalid column passed");
 
+  DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
+
   nscoord maxWidth = aTextRect.width;
   bool widthIsGreater = nsLayoutUtils::StringWidthIsGreaterThan(aText,
                                                                 aFontMetrics,
-                                                                aRenderingContext,
+                                                                drawTarget,
                                                                 maxWidth);
 
   if (aColumn->Overflow()) {
     DebugOnly<nsresult> rv;
     nsTreeColumn* nextColumn = aColumn->GetNext();
     while (nextColumn && widthIsGreater) {
       while (nextColumn) {
         nscoord width;
@@ -1348,17 +1350,17 @@ nsTreeBodyFrame::AdjustForCellText(nsAut
         if (nextText.Length() == 0) {
           nscoord width;
           rv = nextColumn->GetWidthInTwips(this, &width);
           NS_ASSERTION(NS_SUCCEEDED(rv), "nextColumn is invalid");
 
           maxWidth += width;
           widthIsGreater = nsLayoutUtils::StringWidthIsGreaterThan(aText,
                                                                    aFontMetrics,
-                                                                   aRenderingContext,
+                                                                   drawTarget,
                                                                    maxWidth);
 
           nextColumn = nextColumn->GetNext();
         }
         else {
           nextColumn = nullptr;
         }
       }
@@ -1367,18 +1369,17 @@ nsTreeBodyFrame::AdjustForCellText(nsAut
 
   nscoord width;
   if (widthIsGreater) {
     // See if the width is even smaller than the ellipsis
     // If so, clear the text completely.
     const nsDependentString& kEllipsis = nsContentUtils::GetLocalizedEllipsis();
     aFontMetrics.SetTextRunRTL(false);
     nscoord ellipsisWidth =
-      nsLayoutUtils::AppUnitWidthOfString(kEllipsis, aFontMetrics,
-                                          aRenderingContext);
+      nsLayoutUtils::AppUnitWidthOfString(kEllipsis, aFontMetrics, drawTarget);
 
     width = maxWidth;
     if (ellipsisWidth > width)
       aText.SetLength(0);
     else if (ellipsisWidth == width)
       aText.Assign(kEllipsis);
     else {
       // We will be drawing an ellipsis, thank you very much.
@@ -1394,17 +1395,17 @@ nsTreeBodyFrame::AdjustForCellText(nsAut
           nscoord cwidth;
           nscoord twidth = 0;
           uint32_t length = aText.Length();
           uint32_t i;
           for (i = 0; i < length; ++i) {
             char16_t ch = aText[i];
             // XXX this is horrible and doesn't handle clusters
             cwidth = nsLayoutUtils::AppUnitWidthOfString(ch, aFontMetrics,
-                                                         aRenderingContext);
+                                                         drawTarget);
             if (twidth + cwidth > width)
               break;
             twidth += cwidth;
           }
           aText.Truncate(i);
           aText.Append(kEllipsis);
         }
         break;
@@ -1413,17 +1414,17 @@ nsTreeBodyFrame::AdjustForCellText(nsAut
           // Crop left.
           nscoord cwidth;
           nscoord twidth = 0;
           int32_t length = aText.Length();
           int32_t i;
           for (i=length-1; i >= 0; --i) {
             char16_t ch = aText[i];
             cwidth = nsLayoutUtils::AppUnitWidthOfString(ch, aFontMetrics,
-                                                         aRenderingContext);
+                                                         drawTarget);
             if (twidth + cwidth > width)
               break;
             twidth += cwidth;
           }
 
           nsAutoString copy;
           aText.Right(copy, length-1-i);
           aText.Assign(kEllipsis);
@@ -1436,25 +1437,25 @@ nsTreeBodyFrame::AdjustForCellText(nsAut
           // Crop center.
           nsAutoString leftStr, rightStr;
           nscoord cwidth, twidth = 0;
           int32_t length = aText.Length();
           int32_t rightPos = length - 1;
           for (int32_t leftPos = 0; leftPos < rightPos; ++leftPos) {
             char16_t ch = aText[leftPos];
             cwidth = nsLayoutUtils::AppUnitWidthOfString(ch, aFontMetrics,
-                                                         aRenderingContext);
+                                                         drawTarget);
             twidth += cwidth;
             if (twidth > width)
               break;
             leftStr.Append(ch);
 
             ch = aText[rightPos];
             cwidth = nsLayoutUtils::AppUnitWidthOfString(ch, aFontMetrics,
-                                                         aRenderingContext);
+                                                         drawTarget);
             twidth += cwidth;
             if (twidth > width)
               break;
             rightStr.Insert(ch, 0);
             --rightPos;
           }
           aText = leftStr;
           aText.Append(kEllipsis);
--- a/layout/xul/tree/nsTreeBodyFrame.h
+++ b/layout/xul/tree/nsTreeBodyFrame.h
@@ -303,17 +303,18 @@ protected:
   // coordinate system of this frame.
   int32_t GetRowAt(nscoord aX, nscoord aY);
 
   // Check for bidi characters in the text, and if there are any, ensure
   // that the prescontext is in bidi mode.
   void CheckTextForBidi(nsAutoString& aText);
 
   void AdjustForCellText(nsAutoString& aText,
-                         int32_t aRowIndex,  nsTreeColumn* aColumn,
+                         int32_t aRowIndex,
+                         nsTreeColumn* aColumn,
                          nsRenderingContext& aRenderingContext,
                          nsFontMetrics& aFontMetrics,
                          nsRect& aTextRect);
 
   // A helper used when hit testing.
   nsIAtom* GetItemWithinCellAt(nscoord aX, const nsRect& aCellRect,
                                int32_t aRowIndex, nsTreeColumn* aColumn);