Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / graphics / GraphicsContext.cpp
index f43c59c..eb7f457 100644 (file)
 #include "config.h"
 #include "platform/graphics/GraphicsContext.h"
 
+#include "platform/TraceEvent.h"
 #include "platform/geometry/IntRect.h"
 #include "platform/geometry/RoundedRect.h"
 #include "platform/graphics/BitmapImage.h"
 #include "platform/graphics/DisplayList.h"
 #include "platform/graphics/Gradient.h"
 #include "platform/graphics/ImageBuffer.h"
+#include "platform/graphics/UnacceleratedImageBufferSurface.h"
+#include "platform/graphics/skia/SkiaUtils.h"
 #include "platform/text/BidiResolver.h"
 #include "platform/text/TextRunIterator.h"
 #include "platform/weborigin/KURL.h"
 #include "third_party/skia/include/core/SkAnnotation.h"
+#include "third_party/skia/include/core/SkClipStack.h"
 #include "third_party/skia/include/core/SkColorFilter.h"
 #include "third_party/skia/include/core/SkData.h"
 #include "third_party/skia/include/core/SkDevice.h"
 #include "third_party/skia/include/core/SkPicture.h"
+#include "third_party/skia/include/core/SkPictureRecorder.h"
 #include "third_party/skia/include/core/SkRRect.h"
 #include "third_party/skia/include/core/SkRefCnt.h"
+#include "third_party/skia/include/core/SkSurface.h"
 #include "third_party/skia/include/effects/SkBlurMaskFilter.h"
 #include "third_party/skia/include/effects/SkCornerPathEffect.h"
+#include "third_party/skia/include/effects/SkDropShadowImageFilter.h"
 #include "third_party/skia/include/effects/SkLumaColorFilter.h"
+#include "third_party/skia/include/effects/SkMatrixImageFilter.h"
+#include "third_party/skia/include/effects/SkPictureImageFilter.h"
 #include "third_party/skia/include/gpu/GrRenderTarget.h"
 #include "third_party/skia/include/gpu/GrTexture.h"
 #include "wtf/Assertions.h"
 #include "wtf/MathExtras.h"
 
-#if OS(MACOSX)
-#include <ApplicationServices/ApplicationServices.h>
-#endif
-
-using namespace std;
-using blink::WebBlendMode;
-
-namespace WebCore {
-
 namespace {
 
-class CompatibleImageBufferSurface : public ImageBufferSurface {
-    WTF_MAKE_NONCOPYABLE(CompatibleImageBufferSurface); WTF_MAKE_FAST_ALLOCATED;
-public:
-    CompatibleImageBufferSurface(PassRefPtr<SkBaseDevice> device, const IntSize& size, OpacityMode opacityMode)
-        : ImageBufferSurface(size, opacityMode)
-    {
-        m_canvas = adoptPtr(new SkCanvas(device.get())); // Takes a ref on device
-    }
-    virtual ~CompatibleImageBufferSurface() { }
-
-    virtual SkCanvas* canvas() const OVERRIDE { return m_canvas.get(); }
-    virtual bool isValid() const OVERRIDE { return m_canvas; }
-    virtual bool isAccelerated() const OVERRIDE { return isValid() && m_canvas->getTopDevice()->accessRenderTarget(); }
-    virtual Platform3DObject getBackingTexture() const OVERRIDE
-    {
-        ASSERT(isAccelerated());
-        GrRenderTarget* renderTarget = m_canvas->getTopDevice()->accessRenderTarget();
-        if (renderTarget) {
-            return renderTarget->asTexture()->getTextureHandle();
-        }
-        return 0;
-    };
-
-private:
-    OwnPtr<SkCanvas> m_canvas;
-};
-
-} // unnamed namespace
+// Tolerance value use for comparing scale factor to 1..
+// Numerical error should not reach 6th decimal except for highly degenerate cases,
+// and effect of 6th decimal on scale is negligible over max span of a skia canvas
+// which is 32k pixels.
+const float cPictureScaleEpsilon = 0.000001;
 
-struct GraphicsContext::CanvasSaveState {
-    CanvasSaveState(unsigned mask, int count) : m_flags(mask), m_restoreCount(count) { }
+}
 
-    unsigned m_flags;
-    int m_restoreCount;
-};
+namespace blink {
 
 struct GraphicsContext::RecordingState {
-    RecordingState(SkCanvas* currentCanvas, const SkMatrix& currentMatrix, PassRefPtr<DisplayList> displayList)
-        : m_savedCanvas(currentCanvas)
-        , m_displayList(displayList)
+    RecordingState(SkPictureRecorder* recorder, SkCanvas* currentCanvas, const SkMatrix& currentMatrix, bool currentShouldSmoothFonts,
+        PassRefPtr<DisplayList> displayList, RegionTrackingMode trackingMode)
+        : m_displayList(displayList)
+        , m_recorder(recorder)
+        , m_savedCanvas(currentCanvas)
         , m_savedMatrix(currentMatrix)
-    {
-    }
+        , m_savedShouldSmoothFonts(currentShouldSmoothFonts)
+        , m_regionTrackingMode(trackingMode) { }
+
+    ~RecordingState() { }
 
-    SkCanvas* m_savedCanvas;
     RefPtr<DisplayList> m_displayList;
+    SkPictureRecorder* m_recorder;
+    SkCanvas* m_savedCanvas;
     const SkMatrix m_savedMatrix;
+    bool m_savedShouldSmoothFonts;
+    RegionTrackingMode m_regionTrackingMode;
 };
 
-GraphicsContext::GraphicsContext(SkCanvas* canvas)
+GraphicsContext::GraphicsContext(SkCanvas* canvas, DisabledMode disableContextOrPainting)
     : m_canvas(canvas)
     , m_paintStateStack()
     , m_paintStateIndex(0)
-    , m_canvasSaveFlags(0)
     , m_annotationMode(0)
-#if !ASSERT_DISABLED
+#if ENABLE(ASSERT)
     , m_annotationCount(0)
     , m_layerCount(0)
+    , m_disableDestructionChecks(false)
 #endif
-    , m_trackOpaqueRegion(false)
+    , m_disabledState(disableContextOrPainting)
+    , m_deviceScaleFactor(1.0f)
+    , m_regionTrackingMode(RegionTrackingDisabled)
     , m_trackTextRegion(false)
-    , m_useHighResMarker(false)
-    , m_updatingControlTints(false)
     , m_accelerated(false)
     , m_isCertainlyOpaque(true)
     , m_printing(false)
+    , m_antialiasHairlineImages(false)
+    , m_shouldSmoothFonts(true)
 {
     // FIXME: Do some tests to determine how many states are typically used, and allocate
     // several here.
@@ -137,127 +120,138 @@ GraphicsContext::GraphicsContext(SkCanvas* canvas)
 
 GraphicsContext::~GraphicsContext()
 {
-    ASSERT(!m_paintStateIndex);
-    ASSERT(!m_paintState->m_saveCount);
-    ASSERT(!m_annotationCount);
-    ASSERT(!m_layerCount);
-    ASSERT(m_recordingStateStack.isEmpty());
+#if ENABLE(ASSERT)
+    if (!m_disableDestructionChecks) {
+        ASSERT(!m_paintStateIndex);
+        ASSERT(!m_paintState->saveCount());
+        ASSERT(!m_annotationCount);
+        ASSERT(!m_layerCount);
+        ASSERT(m_recordingStateStack.isEmpty());
+        ASSERT(!saveCount());
+    }
+#endif
 }
 
-const SkBitmap* GraphicsContext::bitmap() const
+void GraphicsContext::resetCanvas(SkCanvas* canvas)
 {
-    TRACE_EVENT0("skia", "GraphicsContext::bitmap");
-    return &m_canvas->getDevice()->accessBitmap(false);
+    m_canvas = canvas;
+    m_trackedRegion.reset();
 }
 
-const SkBitmap& GraphicsContext::layerBitmap(AccessMode access) const
+void GraphicsContext::setRegionTrackingMode(RegionTrackingMode mode)
 {
-    return m_canvas->getTopDevice()->accessBitmap(access == ReadWrite);
+    m_regionTrackingMode = mode;
+    if (mode == RegionTrackingOpaque)
+        m_trackedRegion.setTrackedRegionType(RegionTracker::Opaque);
+    else if (mode == RegionTrackingOverwrite)
+        m_trackedRegion.setTrackedRegionType(RegionTracker::Overwrite);
 }
 
 void GraphicsContext::save()
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    m_paintState->m_saveCount++;
+    m_paintState->incrementSaveCount();
 
-    m_canvasStateStack.append(CanvasSaveState(m_canvasSaveFlags, m_canvas->getSaveCount()));
-    m_canvasSaveFlags |= SkCanvas::kMatrixClip_SaveFlag;
+    ASSERT(m_canvas);
+    m_canvas->save();
 }
 
 void GraphicsContext::restore()
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    if (!m_paintStateIndex && !m_paintState->m_saveCount) {
+    if (!m_paintStateIndex && !m_paintState->saveCount()) {
         WTF_LOG_ERROR("ERROR void GraphicsContext::restore() stack is empty");
         return;
     }
 
-    if (m_paintState->m_saveCount) {
-        m_paintState->m_saveCount--;
+    if (m_paintState->saveCount()) {
+        m_paintState->decrementSaveCount();
     } else {
         m_paintStateIndex--;
         m_paintState = m_paintStateStack[m_paintStateIndex].get();
     }
 
-    CanvasSaveState savedState = m_canvasStateStack.last();
-    m_canvasStateStack.removeLast();
-    m_canvasSaveFlags = savedState.m_flags;
-    m_canvas->restoreToCount(savedState.m_restoreCount);
+    ASSERT(m_canvas);
+    m_canvas->restore();
+}
+
+#if ENABLE(ASSERT)
+unsigned GraphicsContext::saveCount() const
+{
+    // Each m_paintStateStack entry implies an additional save op
+    // (on top of its own saveCount), except for the first frame.
+    unsigned count = m_paintStateIndex;
+    ASSERT(m_paintStateStack.size() > m_paintStateIndex);
+    for (unsigned i = 0; i <= m_paintStateIndex; ++i)
+        count += m_paintStateStack[i]->saveCount();
+
+    return count;
 }
+#endif
 
-void GraphicsContext::saveLayer(const SkRect* bounds, const SkPaint* paint, SkCanvas::SaveFlags saveFlags)
+void GraphicsContext::saveLayer(const SkRect* bounds, const SkPaint* paint)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    realizeCanvasSave(SkCanvas::kMatrixClip_SaveFlag);
+    ASSERT(m_canvas);
 
-    m_canvas->saveLayer(bounds, paint, saveFlags);
-    if (bounds)
-        m_canvas->clipRect(*bounds);
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.pushCanvasLayer(paint);
+    m_canvas->saveLayer(bounds, paint);
+    if (regionTrackingEnabled())
+        m_trackedRegion.pushCanvasLayer(paint);
 }
 
 void GraphicsContext::restoreLayer()
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
+    ASSERT(m_canvas);
+
     m_canvas->restore();
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.popCanvasLayer(this);
+    if (regionTrackingEnabled())
+        m_trackedRegion.popCanvasLayer(this);
 }
 
-void GraphicsContext::beginAnnotation(const char* rendererName, const char* paintPhase,
-    const String& elementId, const String& elementClass, const String& elementTag)
+void GraphicsContext::beginAnnotation(const AnnotationList& annotations)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    canvas()->beginCommentGroup("GraphicsContextAnnotation");
+    ASSERT(m_canvas);
 
-    GraphicsContextAnnotation annotation(rendererName, paintPhase, elementId, elementClass, elementTag);
-    AnnotationList annotations;
-    annotation.asAnnotationList(annotations);
+    canvas()->beginCommentGroup("GraphicsContextAnnotation");
 
     AnnotationList::const_iterator end = annotations.end();
     for (AnnotationList::const_iterator it = annotations.begin(); it != end; ++it)
         canvas()->addComment(it->first, it->second.ascii().data());
 
-#if !ASSERT_DISABLED
+#if ENABLE(ASSERT)
     ++m_annotationCount;
 #endif
 }
 
 void GraphicsContext::endAnnotation()
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
+    ASSERT(m_canvas);
+    ASSERT(m_annotationCount > 0);
     canvas()->endCommentGroup();
 
-    ASSERT(m_annotationCount > 0);
-#if !ASSERT_DISABLED
+#if ENABLE(ASSERT)
     --m_annotationCount;
 #endif
 }
 
-void GraphicsContext::setStrokeColor(const Color& color)
-{
-    GraphicsContextState* stateToSet = mutableState();
-    stateToSet->m_strokeData.setColor(color);
-    stateToSet->m_strokeData.clearGradient();
-    stateToSet->m_strokeData.clearPattern();
-}
-
 void GraphicsContext::setStrokePattern(PassRefPtr<Pattern> pattern)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     ASSERT(pattern);
@@ -265,14 +259,13 @@ void GraphicsContext::setStrokePattern(PassRefPtr<Pattern> pattern)
         setStrokeColor(Color::black);
         return;
     }
-    GraphicsContextState* stateToSet = mutableState();
-    stateToSet->m_strokeData.clearGradient();
-    stateToSet->m_strokeData.setPattern(pattern);
+
+    mutableState()->setStrokePattern(pattern);
 }
 
 void GraphicsContext::setStrokeGradient(PassRefPtr<Gradient> gradient)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     ASSERT(gradient);
@@ -280,22 +273,12 @@ void GraphicsContext::setStrokeGradient(PassRefPtr<Gradient> gradient)
         setStrokeColor(Color::black);
         return;
     }
-    GraphicsContextState* stateToSet = mutableState();
-    stateToSet->m_strokeData.setGradient(gradient);
-    stateToSet->m_strokeData.clearPattern();
-}
-
-void GraphicsContext::setFillColor(const Color& color)
-{
-    GraphicsContextState* stateToSet = mutableState();
-    stateToSet->m_fillColor = color;
-    stateToSet->m_fillGradient.clear();
-    stateToSet->m_fillPattern.clear();
+    mutableState()->setStrokeGradient(gradient);
 }
 
 void GraphicsContext::setFillPattern(PassRefPtr<Pattern> pattern)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     ASSERT(pattern);
@@ -304,14 +287,12 @@ void GraphicsContext::setFillPattern(PassRefPtr<Pattern> pattern)
         return;
     }
 
-    GraphicsContextState* stateToSet = mutableState();
-    stateToSet->m_fillGradient.clear();
-    stateToSet->m_fillPattern = pattern;
+    mutableState()->setFillPattern(pattern);
 }
 
 void GraphicsContext::setFillGradient(PassRefPtr<Gradient> gradient)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     ASSERT(gradient);
@@ -320,87 +301,103 @@ void GraphicsContext::setFillGradient(PassRefPtr<Gradient> gradient)
         return;
     }
 
-    GraphicsContextState* stateToSet = mutableState();
-    stateToSet->m_fillGradient = gradient;
-    stateToSet->m_fillPattern.clear();
+    mutableState()->setFillGradient(gradient);
 }
 
 void GraphicsContext::setShadow(const FloatSize& offset, float blur, const Color& color,
-    DrawLooper::ShadowTransformMode shadowTransformMode,
-    DrawLooper::ShadowAlphaMode shadowAlphaMode)
+    DrawLooperBuilder::ShadowTransformMode shadowTransformMode,
+    DrawLooperBuilder::ShadowAlphaMode shadowAlphaMode, ShadowMode shadowMode)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    if (!color.alpha() || (!offset.width() && !offset.height() && !blur)) {
+    OwnPtr<DrawLooperBuilder> drawLooperBuilder = DrawLooperBuilder::create();
+    if (!color.alpha()) {
+        if (shadowMode == DrawShadowOnly) {
+            // shadow only, but there is no shadow: use an empty draw looper to disable rendering of the source primitive
+            setDrawLooper(drawLooperBuilder.release());
+            return;
+        }
         clearShadow();
         return;
     }
 
-    DrawLooper drawLooper;
-    drawLooper.addShadow(offset, blur, color, shadowTransformMode, shadowAlphaMode);
-    drawLooper.addUnmodifiedContent();
-    setDrawLooper(drawLooper);
+    drawLooperBuilder->addShadow(offset, blur, color, shadowTransformMode, shadowAlphaMode);
+    if (shadowMode == DrawShadowAndForeground) {
+        drawLooperBuilder->addUnmodifiedContent();
+    }
+    setDrawLooper(drawLooperBuilder.release());
+
+    if (shadowTransformMode == DrawLooperBuilder::ShadowIgnoresTransforms
+        && shadowAlphaMode == DrawLooperBuilder::ShadowRespectsAlpha) {
+        // This image filter will be used in place of the drawLooper created above but only for drawing non-opaque bitmaps;
+        // see preparePaintForDrawRectToRect().
+        SkColor skColor = color.rgb();
+        // These constants are from RadiusToSigma() from DrawLooperBuilder.cpp.
+        const SkScalar sigma = 0.288675f * blur + 0.5f;
+        SkDropShadowImageFilter::ShadowMode dropShadowMode = shadowMode == DrawShadowAndForeground ? SkDropShadowImageFilter::kDrawShadowAndForeground_ShadowMode : SkDropShadowImageFilter::kDrawShadowOnly_ShadowMode;
+        RefPtr<SkImageFilter> filter = adoptRef(SkDropShadowImageFilter::Create(offset.width(), offset.height(), sigma, sigma, skColor, dropShadowMode));
+        setDropShadowImageFilter(filter);
+    }
 }
 
-void GraphicsContext::setDrawLooper(const DrawLooper& drawLooper)
+void GraphicsContext::setDrawLooper(PassOwnPtr<DrawLooperBuilder> drawLooperBuilder)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    mutableState()->m_looper = drawLooper.skDrawLooper();
+    mutableState()->setDrawLooper(drawLooperBuilder->detachDrawLooper());
 }
 
 void GraphicsContext::clearDrawLooper()
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    mutableState()->m_looper.clear();
+    mutableState()->clearDrawLooper();
 }
 
-bool GraphicsContext::hasShadow() const
+void GraphicsContext::setDropShadowImageFilter(PassRefPtr<SkImageFilter> imageFilter)
 {
-    return !!immutableState()->m_looper;
+    if (contextDisabled())
+        return;
+
+    mutableState()->setDropShadowImageFilter(imageFilter);
 }
 
-int GraphicsContext::getNormalizedAlpha() const
+void GraphicsContext::clearDropShadowImageFilter()
 {
-    int alpha = roundf(immutableState()->m_alpha * 256);
-    if (alpha > 255)
-        alpha = 255;
-    else if (alpha < 0)
-        alpha = 0;
-    return alpha;
+    if (contextDisabled())
+        return;
+
+    mutableState()->clearDropShadowImageFilter();
 }
 
-FloatRect GraphicsContext::getClipBounds() const
+bool GraphicsContext::hasShadow() const
 {
-    if (paintingDisabled())
-        return FloatRect();
-    SkRect rect;
-    if (!m_canvas->getClipBounds(&rect))
-        return FloatRect();
-    return FloatRect(rect);
+    return !!immutableState()->drawLooper() || !!immutableState()->dropShadowImageFilter();
 }
 
 bool GraphicsContext::getTransformedClipBounds(FloatRect* bounds) const
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return false;
+    ASSERT(m_canvas);
     SkIRect skIBounds;
     if (!m_canvas->getClipDeviceBounds(&skIBounds))
         return false;
-    SkRect skBounds = SkRect::MakeFromIRect(skIBounds);
+    SkRect skBounds = SkRect::Make(skIBounds);
     *bounds = FloatRect(skBounds);
     return true;
 }
 
 SkMatrix GraphicsContext::getTotalMatrix() const
 {
-    if (paintingDisabled())
+    if (contextDisabled() || !m_canvas)
         return SkMatrix::I();
 
+    ASSERT(m_canvas);
+
     if (!isRecording())
         return m_canvas->getTotalMatrix();
 
@@ -411,16 +408,9 @@ SkMatrix GraphicsContext::getTotalMatrix() const
     return totalMatrix;
 }
 
-bool GraphicsContext::isPrintingDevice() const
-{
-    if (paintingDisabled())
-        return false;
-    return m_canvas->getTopDevice()->getDeviceCapabilities() & SkBaseDevice::kVector_Capability;
-}
-
-void GraphicsContext::adjustTextRenderMode(SkPaint* paint)
+void GraphicsContext::adjustTextRenderMode(SkPaint* paint) const
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     if (!paint->isLCDRenderText())
@@ -429,13 +419,14 @@ void GraphicsContext::adjustTextRenderMode(SkPaint* paint)
     paint->setLCDRenderText(couldUseLCDRenderedText());
 }
 
-bool GraphicsContext::couldUseLCDRenderedText()
+bool GraphicsContext::couldUseLCDRenderedText() const
 {
+    ASSERT(m_canvas);
     // Our layers only have a single alpha channel. This means that subpixel
     // rendered text cannot be composited correctly when the layer is
-    // collapsed. Therefore, subpixel text is disabled when we are drawing
+    // collapsed. Therefore, subpixel text is contextDisabled when we are drawing
     // onto a layer.
-    if (paintingDisabled() || isDrawingToLayer() || !isCertainlyOpaque())
+    if (contextDisabled() || m_canvas->isDrawingToLayer() || !isCertainlyOpaque())
         return false;
 
     return shouldSmoothFonts();
@@ -443,15 +434,14 @@ bool GraphicsContext::couldUseLCDRenderedText()
 
 void GraphicsContext::setCompositeOperation(CompositeOperator compositeOperation, WebBlendMode blendMode)
 {
-    GraphicsContextState* stateToSet = mutableState();
-    stateToSet->m_compositeOperator = compositeOperation;
-    stateToSet->m_blendMode = blendMode;
-    stateToSet->m_xferMode = WebCoreCompositeToSkiaComposite(compositeOperation, blendMode);
+    if (contextDisabled())
+        return;
+    mutableState()->setCompositeOperation(compositeOperation, blendMode);
 }
 
-SkColorFilter* GraphicsContext::colorFilter()
+SkColorFilter* GraphicsContext::colorFilter() const
 {
-    return immutableState()->m_colorFilter.get();
+    return immutableState()->colorFilter();
 }
 
 void GraphicsContext::setColorFilter(ColorFilter colorFilter)
@@ -460,109 +450,110 @@ void GraphicsContext::setColorFilter(ColorFilter colorFilter)
 
     // We only support one active color filter at the moment. If (when) this becomes a problem,
     // we should switch to using color filter chains (Skia work in progress).
-    ASSERT(!stateToSet->m_colorFilter);
-    stateToSet->m_colorFilter = WebCoreColorFilterToSkiaColorFilter(colorFilter);
+    ASSERT(!stateToSet->colorFilter());
+    stateToSet->setColorFilter(WebCoreColorFilterToSkiaColorFilter(colorFilter));
 }
 
-bool GraphicsContext::readPixels(SkBitmap* bitmap, int x, int y, SkCanvas::Config8888 config8888)
+bool GraphicsContext::readPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, int x, int y)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return false;
 
-    return m_canvas->readPixels(bitmap, x, y, config8888);
+    ASSERT(m_canvas);
+    return m_canvas->readPixels(info, pixels, rowBytes, x, y);
 }
 
 void GraphicsContext::setMatrix(const SkMatrix& matrix)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    realizeCanvasSave(SkCanvas::kMatrix_SaveFlag);
+    ASSERT(m_canvas);
 
     m_canvas->setMatrix(matrix);
 }
 
-bool GraphicsContext::concat(const SkMatrix& matrix)
+void GraphicsContext::concat(const SkMatrix& matrix)
 {
-    if (paintingDisabled())
-        return false;
-
+    if (contextDisabled())
+        return;
 
     if (matrix.isIdentity())
-        return true;
+        return;
 
-    realizeCanvasSave(SkCanvas::kMatrix_SaveFlag);
+    ASSERT(m_canvas);
 
-    return m_canvas->concat(matrix);
+    m_canvas->concat(matrix);
 }
 
 void GraphicsContext::beginTransparencyLayer(float opacity, const FloatRect* bounds)
 {
-    beginLayer(opacity, immutableState()->m_compositeOperator, bounds);
+    beginLayer(opacity, immutableState()->compositeOperator(), bounds);
 }
 
 void GraphicsContext::beginLayer(float opacity, CompositeOperator op, const FloatRect* bounds, ColorFilter colorFilter, ImageFilter* imageFilter)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    // We need the "alpha" layer flag here because the base layer is opaque
-    // (the surface of the page) but layers on top may have transparent parts.
-    // Without explicitly setting the alpha flag, the layer will inherit the
-    // opaque setting of the base and some things won't work properly.
-    SkCanvas::SaveFlags saveFlags = static_cast<SkCanvas::SaveFlags>(SkCanvas::kHasAlphaLayer_SaveFlag | SkCanvas::kFullColorLayer_SaveFlag);
-
     SkPaint layerPaint;
     layerPaint.setAlpha(static_cast<unsigned char>(opacity * 255));
-    layerPaint.setXfermode(WebCoreCompositeToSkiaComposite(op, m_paintState->m_blendMode).get());
+    layerPaint.setXfermodeMode(WebCoreCompositeToSkiaComposite(op, m_paintState->blendMode()));
     layerPaint.setColorFilter(WebCoreColorFilterToSkiaColorFilter(colorFilter).get());
     layerPaint.setImageFilter(imageFilter);
 
     if (bounds) {
         SkRect skBounds = WebCoreFloatRectToSKRect(*bounds);
-        saveLayer(&skBounds, &layerPaint, saveFlags);
+        saveLayer(&skBounds, &layerPaint);
     } else {
-        saveLayer(0, &layerPaint, saveFlags);
+        saveLayer(0, &layerPaint);
     }
 
-#if !ASSERT_DISABLED
+#if ENABLE(ASSERT)
     ++m_layerCount;
 #endif
 }
 
 void GraphicsContext::endLayer()
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     restoreLayer();
 
     ASSERT(m_layerCount > 0);
-#if !ASSERT_DISABLED
+#if ENABLE(ASSERT)
     --m_layerCount;
 #endif
 }
 
-void GraphicsContext::beginRecording(const FloatRect& bounds)
+void GraphicsContext::beginRecording(const FloatRect& bounds, uint32_t recordFlags)
 {
-    RefPtr<DisplayList> displayList = adoptRef(new DisplayList(bounds));
+    RefPtr<DisplayList> displayList = DisplayList::create(bounds);
 
     SkCanvas* savedCanvas = m_canvas;
     SkMatrix savedMatrix = getTotalMatrix();
-
-    IntRect recordingRect = enclosingIntRect(bounds);
-    m_canvas = displayList->picture()->beginRecording(recordingRect.width(), recordingRect.height(),
-        SkPicture::kUsePathBoundsForClip_RecordingFlag);
-
-    // We want the bounds offset mapped to (0, 0), such that the display list content
-    // is fully contained within the SkPictureRecord's bounds.
-    if (!toFloatSize(bounds.location()).isZero()) {
-        m_canvas->translate(-bounds.x(), -bounds.y());
-        // To avoid applying the offset repeatedly in getTotalMatrix(), we pre-apply it here.
-        savedMatrix.preTranslate(bounds.x(), bounds.y());
+    SkPictureRecorder* recorder = 0;
+
+    if (!contextDisabled()) {
+        FloatRect bounds = displayList->bounds();
+        recorder = new SkPictureRecorder;
+        m_canvas = recorder->beginRecording(bounds.width(), bounds.height(), 0, recordFlags);
+
+        // We want the bounds offset mapped to (0, 0), such that the display list content
+        // is fully contained within the SkPictureRecord's bounds.
+        if (!toFloatSize(bounds.location()).isZero()) {
+            m_canvas->translate(-bounds.x(), -bounds.y());
+            // To avoid applying the offset repeatedly in getTotalMatrix(), we pre-apply it here.
+            savedMatrix.preTranslate(bounds.x(), bounds.y());
+        }
     }
 
-    m_recordingStateStack.append(RecordingState(savedCanvas, savedMatrix, displayList));
+    m_recordingStateStack.append(RecordingState(recorder, savedCanvas, savedMatrix, m_shouldSmoothFonts, displayList,
+        static_cast<RegionTrackingMode>(m_regionTrackingMode)));
+
+    // Disable region tracking during recording.
+    setRegionTrackingMode(RegionTrackingDisabled);
 }
 
 PassRefPtr<DisplayList> GraphicsContext::endRecording()
@@ -570,13 +561,16 @@ PassRefPtr<DisplayList> GraphicsContext::endRecording()
     ASSERT(!m_recordingStateStack.isEmpty());
 
     RecordingState recording = m_recordingStateStack.last();
-    ASSERT(recording.m_displayList->picture()->getRecordingCanvas());
-    recording.m_displayList->picture()->endRecording();
+    if (!contextDisabled())
+        recording.m_displayList->setPicture(recording.m_recorder->endRecording());
 
-    m_recordingStateStack.removeLast();
     m_canvas = recording.m_savedCanvas;
+    setRegionTrackingMode(recording.m_regionTrackingMode);
+    setShouldSmoothFonts(recording.m_savedShouldSmoothFonts);
+    delete recording.m_recorder;
+    m_recordingStateStack.removeLast();
 
-    return recording.m_displayList.release();
+    return recording.m_displayList;
 }
 
 bool GraphicsContext::isRecording() const
@@ -587,105 +581,196 @@ bool GraphicsContext::isRecording() const
 void GraphicsContext::drawDisplayList(DisplayList* displayList)
 {
     ASSERT(displayList);
-    ASSERT(!displayList->picture()->getRecordingCanvas());
+    ASSERT(m_canvas);
 
-    if (paintingDisabled() || displayList->bounds().isEmpty())
+    if (contextDisabled() || displayList->bounds().isEmpty())
         return;
 
-    realizeCanvasSave(SkCanvas::kMatrixClip_SaveFlag);
+    bool performClip = !displayList->clip().isEmpty();
+    bool performTransform = !displayList->transform().isIdentity();
+    if (performClip || performTransform) {
+        save();
+        if (performTransform)
+            concat(displayList->transform());
+        if (performClip)
+            clipRect(displayList->clip());
+    }
 
-    const FloatRect& bounds = displayList->bounds();
-    if (bounds.x() || bounds.y())
-        m_canvas->translate(bounds.x(), bounds.y());
+    const FloatPoint& location = displayList->bounds().location();
+    if (location.x() || location.y()) {
+        SkMatrix m;
+        m.setTranslate(location.x(), location.y());
+        m_canvas->drawPicture(displayList->picture().get(), &m, 0);
+    } else {
+        m_canvas->drawPicture(displayList->picture().get());
+    }
 
-    m_canvas->drawPicture(*displayList->picture());
+    if (regionTrackingEnabled()) {
+        // Since we don't track regions within display lists, conservatively
+        // mark the bounds as non-opaque.
+        SkPaint paint;
+        paint.setXfermodeMode(SkXfermode::kClear_Mode);
+        m_trackedRegion.didDrawBounded(this, displayList->bounds(), paint);
+    }
 
-    if (bounds.x() || bounds.y())
-        m_canvas->translate(-bounds.x(), -bounds.y());
+    if (performClip || performTransform)
+        restore();
 }
 
-void GraphicsContext::setupPaintForFilling(SkPaint* paint) const
+void GraphicsContext::drawPicture(SkPicture* picture, const FloatPoint& location)
 {
-    if (paintingDisabled())
+    ASSERT(picture);
+    ASSERT(m_canvas);
+
+    if (contextDisabled())
         return;
 
-    setupPaintCommon(paint);
+    if (location.x() || location.y()) {
+        SkMatrix m;
+        m.setTranslate(location.x(), location.y());
+        m_canvas->drawPicture(picture, &m, 0);
+    } else {
+        m_canvas->drawPicture(picture);
+    }
 
-    setupShader(paint, immutableState()->m_fillGradient.get(), immutableState()->m_fillPattern.get(), immutableState()->m_fillColor.rgb());
+    if (regionTrackingEnabled()) {
+        // Since we don't track regions within pictures, conservatively
+        // mark the bounds as non-opaque.
+        SkPaint paint;
+        paint.setXfermodeMode(SkXfermode::kClear_Mode);
+        FloatRect bound = picture->cullRect();
+        bound.moveBy(location);
+        m_trackedRegion.didDrawBounded(this, bound, paint);
+    }
 }
 
-float GraphicsContext::setupPaintForStroking(SkPaint* paint, int length) const
+static inline bool pictureScaleIsApproximatelyOne(float x)
 {
-    if (paintingDisabled())
-        return 0.0f;
+    return fabsf(x - 1.0f) < cPictureScaleEpsilon;
+}
 
-    setupPaintCommon(paint);
+void GraphicsContext::drawPicture(SkPicture* picture, const FloatRect& dest, const FloatRect& src, CompositeOperator op, WebBlendMode blendMode)
+{
+    ASSERT(m_canvas);
+    if (contextDisabled() || !picture)
+        return;
 
-    setupShader(paint, immutableState()->m_strokeData.gradient(), immutableState()->m_strokeData.pattern(),
-        immutableState()->m_strokeData.color().rgb());
+    SkMatrix ctm = m_canvas->getTotalMatrix();
+    SkRect deviceDest;
+    ctm.mapRect(&deviceDest, dest);
+    float scaleX = deviceDest.width() / src.width();
+    float scaleY = deviceDest.height() / src.height();
 
-    return immutableState()->m_strokeData.setupPaint(paint, length);
+    SkPaint picturePaint;
+    picturePaint.setXfermodeMode(WebCoreCompositeToSkiaComposite(op, blendMode));
+    SkRect sourceBounds = WebCoreFloatRectToSKRect(src);
+    if (pictureScaleIsApproximatelyOne(scaleX * m_deviceScaleFactor) && pictureScaleIsApproximatelyOne(scaleY * m_deviceScaleFactor)) {
+        // Fast path for canvases that are rasterized at screen resolution
+        SkRect skBounds = WebCoreFloatRectToSKRect(dest);
+        m_canvas->saveLayer(&skBounds, &picturePaint);
+        SkMatrix pictureTransform;
+        pictureTransform.setRectToRect(sourceBounds, skBounds, SkMatrix::kFill_ScaleToFit);
+        m_canvas->concat(pictureTransform);
+        m_canvas->drawPicture(picture);
+        m_canvas->restore();
+    } else {
+        RefPtr<SkPictureImageFilter> pictureFilter = adoptRef(SkPictureImageFilter::Create(picture, sourceBounds));
+        SkMatrix layerScale;
+        layerScale.setScale(scaleX, scaleY);
+        RefPtr<SkMatrixImageFilter> matrixFilter = adoptRef(SkMatrixImageFilter::Create(layerScale, SkPaint::kLow_FilterLevel, pictureFilter.get()));
+        picturePaint.setImageFilter(matrixFilter.get());
+        SkRect layerBounds = SkRect::MakeWH(std::max(deviceDest.width(), sourceBounds.width()), std::max(deviceDest.height(), sourceBounds.height()));
+        m_canvas->save();
+        m_canvas->resetMatrix();
+        m_canvas->translate(deviceDest.x(), deviceDest.y());
+        m_canvas->saveLayer(&layerBounds, &picturePaint);
+        m_canvas->restore();
+        m_canvas->restore();
+    }
 }
 
-void GraphicsContext::drawConvexPolygon(size_t numPoints, const FloatPoint* points, bool shouldAntialias)
+void GraphicsContext::fillPolygon(size_t numPoints, const FloatPoint* points, const Color& color,
+    bool shouldAntialias)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    if (numPoints <= 1)
-        return;
+    ASSERT(numPoints > 2);
 
     SkPath path;
-    setPathFromConvexPoints(&path, numPoints, points);
+    setPathFromPoints(&path, numPoints, points);
 
-    SkPaint paint;
-    setupPaintForFilling(&paint);
+    SkPaint paint(immutableState()->fillPaint());
     paint.setAntiAlias(shouldAntialias);
+    paint.setColor(color.rgb());
+
     drawPath(path, paint);
+}
 
-    if (strokeStyle() != NoStroke) {
-        paint.reset();
-        setupPaintForStroking(&paint);
-        drawPath(path, paint);
-    }
+float GraphicsContext::prepareFocusRingPaint(SkPaint& paint, const Color& color, int width) const
+{
+    paint.setAntiAlias(true);
+    paint.setStyle(SkPaint::kStroke_Style);
+    paint.setColor(color.rgb());
+    paint.setStrokeWidth(focusRingWidth(width));
+
+#if OS(MACOSX)
+    paint.setAlpha(64);
+    return (width - 1) * 0.5f;
+#else
+    return 1;
+#endif
 }
 
-// This method is only used to draw the little circles used in lists.
-void GraphicsContext::drawEllipse(const IntRect& elipseRect)
+void GraphicsContext::drawFocusRingPath(const SkPath& path, const Color& color, int width)
 {
-    if (paintingDisabled())
-        return;
+    SkPaint paint;
+    float cornerRadius = prepareFocusRingPaint(paint, color, width);
+
+    paint.setPathEffect(SkCornerPathEffect::Create(SkFloatToScalar(cornerRadius)))->unref();
+
+    // Outer path
+    drawPath(path, paint);
+
+#if OS(MACOSX)
+    // Inner path
+    paint.setAlpha(128);
+    paint.setStrokeWidth(paint.getStrokeWidth() * 0.5f);
+    drawPath(path, paint);
+#endif
+}
 
-    SkRect rect = elipseRect;
+void GraphicsContext::drawFocusRingRect(const SkRect& rect, const Color& color, int width)
+{
     SkPaint paint;
-    setupPaintForFilling(&paint);
-    drawOval(rect, paint);
+    float cornerRadius = prepareFocusRingPaint(paint, color, width);
 
-    if (strokeStyle() != NoStroke) {
-        paint.reset();
-        setupPaintForStroking(&paint);
-        drawOval(rect, paint);
-    }
+    SkRRect rrect;
+    rrect.setRectXY(rect, SkFloatToScalar(cornerRadius), SkFloatToScalar(cornerRadius));
+
+    // Outer rect
+    drawRRect(rrect, paint);
+
+#if OS(MACOSX)
+    // Inner rect
+    paint.setAlpha(128);
+    paint.setStrokeWidth(paint.getStrokeWidth() * 0.5f);
+    drawRRect(rrect, paint);
+#endif
 }
 
 void GraphicsContext::drawFocusRing(const Path& focusRingPath, int width, int offset, const Color& color)
 {
     // FIXME: Implement support for offset.
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    SkPaint paint;
-    paint.setAntiAlias(true);
-    paint.setStyle(SkPaint::kStroke_Style);
-    paint.setColor(color.rgb());
-
-    drawOuterPath(focusRingPath.skPath(), paint, width);
-    drawInnerPath(focusRingPath.skPath(), paint, width);
+    drawFocusRingPath(focusRingPath.skPath(), color, width);
 }
 
 void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int width, int offset, const Color& color)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     unsigned rectCount = rects.size();
@@ -693,22 +778,20 @@ void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int width, int
         return;
 
     SkRegion focusRingRegion;
-    const int focusRingOutset = getFocusRingOutset(offset);
+    const int outset = focusRingOutset(offset);
     for (unsigned i = 0; i < rectCount; i++) {
         SkIRect r = rects[i];
-        r.inset(-focusRingOutset, -focusRingOutset);
+        r.inset(-outset, -outset);
         focusRingRegion.op(r, SkRegion::kUnion_Op);
     }
 
-    SkPath path;
-    SkPaint paint;
-    paint.setAntiAlias(true);
-    paint.setStyle(SkPaint::kStroke_Style);
-
-    paint.setColor(color.rgb());
-    focusRingRegion.getBoundaryPath(&path);
-    drawOuterPath(path, paint, width);
-    drawInnerPath(path, paint, width);
+    if (focusRingRegion.isRect()) {
+        drawFocusRingRect(SkRect::MakeFromIRect(focusRingRegion.getBounds()), color, width);
+    } else {
+        SkPath path;
+        if (focusRingRegion.getBoundaryPath(&path))
+            drawFocusRingPath(path, color, width);
+    }
 }
 
 static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowBlur, int shadowSpread, const IntSize& shadowOffset)
@@ -727,6 +810,9 @@ static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shado
 
 void GraphicsContext::drawInnerShadow(const RoundedRect& rect, const Color& shadowColor, const IntSize shadowOffset, int shadowBlur, int shadowSpread, Edges clippedEdges)
 {
+    if (contextDisabled())
+        return;
+
     IntRect holeRect(rect.rect());
     holeRect.inflate(-shadowSpread);
 
@@ -739,17 +825,17 @@ void GraphicsContext::drawInnerShadow(const RoundedRect& rect, const Color& shad
     }
 
     if (clippedEdges & LeftEdge) {
-        holeRect.move(-max(shadowOffset.width(), 0) - shadowBlur, 0);
-        holeRect.setWidth(holeRect.width() + max(shadowOffset.width(), 0) + shadowBlur);
+        holeRect.move(-std::max(shadowOffset.width(), 0) - shadowBlur, 0);
+        holeRect.setWidth(holeRect.width() + std::max(shadowOffset.width(), 0) + shadowBlur);
     }
     if (clippedEdges & TopEdge) {
-        holeRect.move(0, -max(shadowOffset.height(), 0) - shadowBlur);
-        holeRect.setHeight(holeRect.height() + max(shadowOffset.height(), 0) + shadowBlur);
+        holeRect.move(0, -std::max(shadowOffset.height(), 0) - shadowBlur);
+        holeRect.setHeight(holeRect.height() + std::max(shadowOffset.height(), 0) + shadowBlur);
     }
     if (clippedEdges & RightEdge)
-        holeRect.setWidth(holeRect.width() - min(shadowOffset.width(), 0) + shadowBlur);
+        holeRect.setWidth(holeRect.width() - std::min(shadowOffset.width(), 0) + shadowBlur);
     if (clippedEdges & BottomEdge)
-        holeRect.setHeight(holeRect.height() - min(shadowOffset.height(), 0) + shadowBlur);
+        holeRect.setHeight(holeRect.height() - std::min(shadowOffset.height(), 0) + shadowBlur);
 
     Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
 
@@ -766,26 +852,25 @@ void GraphicsContext::drawInnerShadow(const RoundedRect& rect, const Color& shad
         clip(rect.rect());
     }
 
-    DrawLooper drawLooper;
-    drawLooper.addShadow(shadowOffset, shadowBlur, shadowColor,
-        DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
-    setDrawLooper(drawLooper);
+    OwnPtr<DrawLooperBuilder> drawLooperBuilder = DrawLooperBuilder::create();
+    drawLooperBuilder->addShadow(shadowOffset, shadowBlur, shadowColor,
+        DrawLooperBuilder::ShadowRespectsTransforms, DrawLooperBuilder::ShadowIgnoresAlpha);
+    setDrawLooper(drawLooperBuilder.release());
     fillRectWithRoundedHole(outerRect, roundedHole, fillColor);
     restore();
     clearDrawLooper();
 }
 
-// This is only used to draw borders.
 void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     StrokeStyle penStyle = strokeStyle();
     if (penStyle == NoStroke)
         return;
 
-    SkPaint paint;
     FloatPoint p1 = point1;
     FloatPoint p2 = point2;
     bool isVerticalLine = (p1.x() == p2.x());
@@ -796,12 +881,11 @@ void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
     // probably worth the speed up of no square root, which also won't be exact.
     FloatSize disp = p2 - p1;
     int length = SkScalarRoundToInt(disp.width() + disp.height());
-    setupPaintForStroking(&paint, length);
+    SkPaint paint(immutableState()->strokePaint(length));
 
     if (strokeStyle() == DottedStroke || strokeStyle() == DashedStroke) {
         // Do a rect fill of our endpoints.  This ensures we always have the
         // appearance of being a border.  We then draw the actual dotted/dashed line.
-
         SkRect r1, r2;
         r1.set(p1.x(), p1.y(), p1.x() + width, p1.y() + width);
         r2.set(p2.x(), p2.y(), p2.x() + width, p2.y() + width);
@@ -820,20 +904,21 @@ void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
     }
 
     adjustLineToPixelBoundaries(p1, p2, width, penStyle);
-    SkPoint pts[2] = { (SkPoint)p1, (SkPoint)p2 };
+    SkPoint pts[2] = { p1.data(), p2.data() };
 
     m_canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, paint);
 
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawPoints(this, SkCanvas::kLines_PointMode, 2, pts, paint);
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawPoints(this, SkCanvas::kLines_PointMode, 2, pts, paint);
 }
 
 void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float width, DocumentMarkerLineStyle style)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    int deviceScaleFactor = m_useHighResMarker ? 2 : 1;
+    // Use 2x resources for a device scale factor of 1.5 or above.
+    int deviceScaleFactor = m_deviceScaleFactor > 1.5f ? 2 : 1;
 
     // Create the pattern we'll use to draw the underline.
     int index = style == DocumentMarkerGrammarLineStyle ? 1 : 0;
@@ -845,12 +930,11 @@ void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float widt
         // Match the artwork used by the Mac.
         const int rowPixels = 4 * deviceScaleFactor;
         const int colPixels = 3 * deviceScaleFactor;
-        misspellBitmap[index] = new SkBitmap;
-        misspellBitmap[index]->setConfig(SkBitmap::kARGB_8888_Config,
-                                         rowPixels, colPixels);
-        misspellBitmap[index]->allocPixels();
+        SkBitmap bitmap;
+        if (!bitmap.tryAllocN32Pixels(rowPixels, colPixels))
+            return;
 
-        misspellBitmap[index]->eraseARGB(0, 0, 0, 0);
+        bitmap.eraseARGB(0, 0, 0, 0);
         const uint32_t transparentColor = 0x00000000;
 
         if (deviceScaleFactor == 1) {
@@ -863,7 +947,7 @@ void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float widt
             //          c d c   c d c
             //          e f e   e f e
             for (int x = 0; x < colPixels; ++x) {
-                uint32_t* row = misspellBitmap[index]->getAddr32(0, x);
+                uint32_t* row = bitmap.getAddr32(0, x);
                 row[0] = colors[index][x * 2];
                 row[1] = colors[index][x * 2 + 1];
                 row[2] = colors[index][x * 2];
@@ -884,7 +968,7 @@ void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float widt
             //          n o p p o n
             //          q r s s r q
             for (int x = 0; x < colPixels; ++x) {
-                uint32_t* row = misspellBitmap[index]->getAddr32(0, x);
+                uint32_t* row = bitmap.getAddr32(0, x);
                 row[0] = colors[index][x * 3];
                 row[1] = colors[index][x * 3 + 1];
                 row[2] = colors[index][x * 3 + 2];
@@ -896,23 +980,27 @@ void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float widt
             }
         } else
             ASSERT_NOT_REACHED();
+
+        misspellBitmap[index] = new SkBitmap(bitmap);
 #else
         // We use a 2-pixel-high misspelling indicator because that seems to be
         // what WebKit is designed for, and how much room there is in a typical
         // page for it.
         const int rowPixels = 32 * deviceScaleFactor; // Must be multiple of 4 for pattern below.
         const int colPixels = 2 * deviceScaleFactor;
-        misspellBitmap[index] = new SkBitmap;
-        misspellBitmap[index]->setConfig(SkBitmap::kARGB_8888_Config, rowPixels, colPixels);
-        misspellBitmap[index]->allocPixels();
+        SkBitmap bitmap;
+        if (!bitmap.tryAllocN32Pixels(rowPixels, colPixels))
+            return;
 
-        misspellBitmap[index]->eraseARGB(0, 0, 0, 0);
+        bitmap.eraseARGB(0, 0, 0, 0);
         if (deviceScaleFactor == 1)
-            draw1xMarker(misspellBitmap[index], index);
+            draw1xMarker(&bitmap, index);
         else if (deviceScaleFactor == 2)
-            draw2xMarker(misspellBitmap[index], index);
+            draw2xMarker(&bitmap, index);
         else
             ASSERT_NOT_REACHED();
+
+        misspellBitmap[index] = new SkBitmap(bitmap);
 #endif
     }
 
@@ -934,11 +1022,10 @@ void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float widt
     originY *= deviceScaleFactor;
 #endif
 
+    SkMatrix localMatrix;
+    localMatrix.setTranslate(originX, originY);
     RefPtr<SkShader> shader = adoptRef(SkShader::CreateBitmapShader(
-        *misspellBitmap[index], SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
-    SkMatrix matrix;
-    matrix.setTranslate(originX, originY);
-    shader->setLocalMatrix(matrix);
+        *misspellBitmap[index], SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode, &localMatrix));
 
     SkPaint paint;
     paint.setShader(shader.get());
@@ -948,7 +1035,7 @@ void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float widt
 
     if (deviceScaleFactor == 2) {
         save();
-        scale(FloatSize(0.5, 0.5));
+        scale(0.5, 0.5);
     }
     drawRect(rect, paint);
     if (deviceScaleFactor == 2)
@@ -957,44 +1044,47 @@ void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float widt
 
 void GraphicsContext::drawLineForText(const FloatPoint& pt, float width, bool printing)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     if (width <= 0)
         return;
 
-    int thickness = SkMax32(static_cast<int>(strokeThickness()), 1);
-    SkRect r;
-    r.fLeft = WebCoreFloatToSkScalar(pt.x());
-    // Avoid anti-aliasing lines. Currently, these are always horizontal.
-    // Round to nearest pixel to match text and other content.
-    r.fTop = WebCoreFloatToSkScalar(floorf(pt.y() + 0.5f));
-    r.fRight = r.fLeft + WebCoreFloatToSkScalar(width);
-    r.fBottom = r.fTop + SkIntToScalar(thickness);
-
     SkPaint paint;
     switch (strokeStyle()) {
     case NoStroke:
     case SolidStroke:
     case DoubleStroke:
-    case WavyStroke:
-        setupPaintForFilling(&paint);
-        break;
+    case WavyStroke: {
+        int thickness = SkMax32(static_cast<int>(strokeThickness()), 1);
+        SkRect r;
+        r.fLeft = WebCoreFloatToSkScalar(pt.x());
+        // Avoid anti-aliasing lines. Currently, these are always horizontal.
+        // Round to nearest pixel to match text and other content.
+        r.fTop = WebCoreFloatToSkScalar(floorf(pt.y() + 0.5f));
+        r.fRight = r.fLeft + WebCoreFloatToSkScalar(width);
+        r.fBottom = r.fTop + SkIntToScalar(thickness);
+        paint = immutableState()->fillPaint();
+        // Text lines are drawn using the stroke color.
+        paint.setColor(effectiveStrokeColor());
+        drawRect(r, paint);
+        return;
+    }
     case DottedStroke:
-    case DashedStroke:
-        setupPaintForStroking(&paint);
-        break;
+    case DashedStroke: {
+        int y = floorf(pt.y() + std::max<float>(strokeThickness() / 2.0f, 0.5f));
+        drawLine(IntPoint(pt.x(), y), IntPoint(pt.x() + width, y));
+        return;
+    }
     }
 
-    // Text lines are drawn using the stroke color.
-    paint.setColor(effectiveStrokeColor());
-    drawRect(r, paint);
+    ASSERT_NOT_REACHED();
 }
 
 // Draws a filled rectangle with a stroked border.
 void GraphicsContext::drawRect(const IntRect& rect)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     ASSERT(!rect.isEmpty());
@@ -1002,34 +1092,26 @@ void GraphicsContext::drawRect(const IntRect& rect)
         return;
 
     SkRect skRect = rect;
-    SkPaint paint;
-    int fillcolorNotTransparent = m_paintState->m_fillColor.rgb() & 0xFF000000;
-    if (fillcolorNotTransparent) {
-        setupPaintForFilling(&paint);
+    int fillcolorNotTransparent = immutableState()->fillColor().rgb() & 0xFF000000;
+    if (fillcolorNotTransparent)
+        drawRect(skRect, immutableState()->fillPaint());
+
+    if (immutableState()->strokeData().style() != NoStroke
+        && immutableState()->strokeColor().alpha()) {
+        // Stroke a width: 1 inset border
+        SkPaint paint(immutableState()->fillPaint());
+        paint.setColor(effectiveStrokeColor());
+        paint.setStyle(SkPaint::kStroke_Style);
+        paint.setStrokeWidth(1);
+
+        skRect.inset(0.5f, 0.5f);
         drawRect(skRect, paint);
     }
-
-    if (m_paintState->m_strokeData.style() != NoStroke && (m_paintState->m_strokeData.color().rgb() & 0xFF000000)) {
-        // We do a fill of four rects to simulate the stroke of a border.
-        paint.reset();
-        setupPaintForFilling(&paint);
-        // need to jam in the strokeColor
-        paint.setColor(this->effectiveStrokeColor());
-
-        SkRect topBorder = { skRect.fLeft, skRect.fTop, skRect.fRight, skRect.fTop + 1 };
-        drawRect(topBorder, paint);
-        SkRect bottomBorder = { skRect.fLeft, skRect.fBottom - 1, skRect.fRight, skRect.fBottom };
-        drawRect(bottomBorder, paint);
-        SkRect leftBorder = { skRect.fLeft, skRect.fTop + 1, skRect.fLeft + 1, skRect.fBottom - 1 };
-        drawRect(leftBorder, paint);
-        SkRect rightBorder = { skRect.fRight - 1, skRect.fTop + 1, skRect.fRight, skRect.fBottom - 1 };
-        drawRect(rightBorder, paint);
-    }
 }
 
 void GraphicsContext::drawText(const Font& font, const TextRunPaintInfo& runInfo, const FloatPoint& point)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     font.drawText(this, runInfo, point);
@@ -1037,7 +1119,7 @@ void GraphicsContext::drawText(const Font& font, const TextRunPaintInfo& runInfo
 
 void GraphicsContext::drawEmphasisMarks(const Font& font, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     font.drawEmphasisMarks(this, runInfo, mark, point);
@@ -1045,7 +1127,7 @@ void GraphicsContext::drawEmphasisMarks(const Font& font, const TextRunPaintInfo
 
 void GraphicsContext::drawBidiText(const Font& font, const TextRunPaintInfo& runInfo, const FloatPoint& point, Font::CustomFontNotReadyAction customFontNotReadyAction)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     // sub-run painting is not supported for Bidi text.
@@ -1072,12 +1154,10 @@ void GraphicsContext::drawBidiText(const Font& font, const TextRunPaintInfo& run
 
         TextRunPaintInfo subrunInfo(subrun);
         subrunInfo.bounds = runInfo.bounds;
-        font.drawText(this, subrunInfo, currPoint, customFontNotReadyAction);
+        float runWidth = font.drawUncachedText(this, subrunInfo, currPoint, customFontNotReadyAction);
 
         bidiRun = bidiRun->next();
-        // FIXME: Have Font::drawText return the width of what it drew so that we don't have to re-measure here.
-        if (bidiRun)
-            currPoint.move(font.width(subrun), 0);
+        currPoint.move(runWidth, 0);
     }
 
     bidiRuns.deleteRuns();
@@ -1085,7 +1165,7 @@ void GraphicsContext::drawBidiText(const Font& font, const TextRunPaintInfo& run
 
 void GraphicsContext::drawHighlightForText(const Font& font, const TextRun& run, const FloatPoint& point, int h, const Color& backgroundColor, int from, int to)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     fillRect(font.selectionRectForText(run, point, h, from, to), backgroundColor);
@@ -1098,21 +1178,16 @@ void GraphicsContext::drawImage(Image* image, const IntPoint& p, CompositeOperat
     drawImage(image, FloatRect(IntRect(p, image->size())), FloatRect(FloatPoint(), FloatSize(image->size())), op, shouldRespectImageOrientation);
 }
 
-void GraphicsContext::drawImage(Image* image, const IntRect& r, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
+void GraphicsContext::drawImage(Image* image, const IntRect& r, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation)
 {
     if (!image)
         return;
-    drawImage(image, FloatRect(r), FloatRect(FloatPoint(), FloatSize(image->size())), op, shouldRespectImageOrientation, useLowQualityScale);
+    drawImage(image, FloatRect(r), FloatRect(FloatPoint(), FloatSize(image->size())), op, shouldRespectImageOrientation);
 }
 
-void GraphicsContext::drawImage(Image* image, const IntPoint& dest, const IntRect& srcRect, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation)
+void GraphicsContext::drawImage(Image* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation)
 {
-    drawImage(image, FloatRect(IntRect(dest, srcRect.size())), FloatRect(srcRect), op, shouldRespectImageOrientation);
-}
-
-void GraphicsContext::drawImage(Image* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
-{
-    drawImage(image, dest, src, op, blink::WebBlendModeNormal, shouldRespectImageOrientation, useLowQualityScale);
+    drawImage(image, dest, src, op, WebBlendModeNormal, shouldRespectImageOrientation);
 }
 
 void GraphicsContext::drawImage(Image* image, const FloatRect& dest)
@@ -1122,42 +1197,24 @@ void GraphicsContext::drawImage(Image* image, const FloatRect& dest)
     drawImage(image, dest, FloatRect(IntRect(IntPoint(), image->size())));
 }
 
-void GraphicsContext::drawImage(Image* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, WebBlendMode blendMode, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
-{    if (paintingDisabled() || !image)
+void GraphicsContext::drawImage(Image* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, WebBlendMode blendMode, RespectImageOrientationEnum shouldRespectImageOrientation)
+{
+    if (contextDisabled() || !image)
         return;
-
-    InterpolationQuality previousInterpolationQuality = InterpolationDefault;
-
-    if (useLowQualityScale) {
-        previousInterpolationQuality = imageInterpolationQuality();
-        setImageInterpolationQuality(InterpolationLow);
-    }
-
     image->draw(this, dest, src, op, blendMode, shouldRespectImageOrientation);
-
-    if (useLowQualityScale)
-        setImageInterpolationQuality(previousInterpolationQuality);
 }
 
-void GraphicsContext::drawTiledImage(Image* image, const IntRect& destRect, const IntPoint& srcPoint, const IntSize& tileSize, CompositeOperator op, bool useLowQualityScale, WebBlendMode blendMode, const IntSize& repeatSpacing)
+void GraphicsContext::drawTiledImage(Image* image, const IntRect& destRect, const IntPoint& srcPoint, const IntSize& tileSize, CompositeOperator op, WebBlendMode blendMode, const IntSize& repeatSpacing)
 {
-    if (paintingDisabled() || !image)
+    if (contextDisabled() || !image)
         return;
-
-    if (useLowQualityScale) {
-        InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
-        setImageInterpolationQuality(InterpolationLow);
-        image->drawTiled(this, destRect, srcPoint, tileSize, op, blendMode, repeatSpacing);
-        setImageInterpolationQuality(previousInterpolationQuality);
-    } else {
-        image->drawTiled(this, destRect, srcPoint, tileSize, op, blendMode, repeatSpacing);
-    }
+    image->drawTiled(this, destRect, srcPoint, tileSize, op, blendMode, repeatSpacing);
 }
 
 void GraphicsContext::drawTiledImage(Image* image, const IntRect& dest, const IntRect& srcRect,
-    const FloatSize& tileScaleFactor, Image::TileRule hRule, Image::TileRule vRule, CompositeOperator op, bool useLowQualityScale)
+    const FloatSize& tileScaleFactor, Image::TileRule hRule, Image::TileRule vRule, CompositeOperator op)
 {
-    if (paintingDisabled() || !image)
+    if (contextDisabled() || !image)
         return;
 
     if (hRule == Image::StretchTile && vRule == Image::StretchTile) {
@@ -1166,233 +1223,257 @@ void GraphicsContext::drawTiledImage(Image* image, const IntRect& dest, const In
         return;
     }
 
-    if (useLowQualityScale) {
-        InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
-        setImageInterpolationQuality(InterpolationLow);
-        image->drawTiled(this, dest, srcRect, tileScaleFactor, hRule, vRule, op);
-        setImageInterpolationQuality(previousInterpolationQuality);
-    } else {
-        image->drawTiled(this, dest, srcRect, tileScaleFactor, hRule, vRule, op);
-    }
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntPoint& p, CompositeOperator op, WebBlendMode blendMode)
-{
-    if (!image)
-        return;
-    drawImageBuffer(image, FloatRect(IntRect(p, image->size())), FloatRect(FloatPoint(), FloatSize(image->size())), op, blendMode);
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntRect& r, CompositeOperator op, WebBlendMode blendMode, bool useLowQualityScale)
-{
-    if (!image)
-        return;
-    drawImageBuffer(image, FloatRect(r), FloatRect(FloatPoint(), FloatSize(image->size())), op, blendMode, useLowQualityScale);
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntPoint& dest, const IntRect& srcRect, CompositeOperator op, WebBlendMode blendMode)
-{
-    drawImageBuffer(image, FloatRect(IntRect(dest, srcRect.size())), FloatRect(srcRect), op, blendMode);
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntRect& dest, const IntRect& srcRect, CompositeOperator op, WebBlendMode blendMode, bool useLowQualityScale)
-{
-    drawImageBuffer(image, FloatRect(dest), FloatRect(srcRect), op, blendMode, useLowQualityScale);
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatRect& dest)
-{
-    if (!image)
-        return;
-    drawImageBuffer(image, dest, FloatRect(IntRect(IntPoint(), image->size())));
+    image->drawTiled(this, dest, srcRect, tileScaleFactor, hRule, vRule, op);
 }
 
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, WebBlendMode blendMode, bool useLowQualityScale)
+void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatRect& dest,
+    const FloatRect* src, CompositeOperator op, WebBlendMode blendMode)
 {
-    if (paintingDisabled() || !image)
+    if (contextDisabled() || !image)
         return;
 
-    if (useLowQualityScale) {
-        InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
-        setImageInterpolationQuality(InterpolationLow);
-        image->draw(this, dest, src, op, blendMode, useLowQualityScale);
-        setImageInterpolationQuality(previousInterpolationQuality);
-    } else {
-        image->draw(this, dest, src, op, blendMode, useLowQualityScale);
-    }
+    image->draw(this, dest, src, op, blendMode);
 }
 
-void GraphicsContext::writePixels(const SkBitmap& bitmap, int x, int y, SkCanvas::Config8888 config8888)
+void GraphicsContext::writePixels(const SkImageInfo& info, const void* pixels, size_t rowBytes, int x, int y)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
-    m_canvas->writePixels(bitmap, x, y, config8888);
+    m_canvas->writePixels(info, pixels, rowBytes, x, y);
 
-    if (m_trackOpaqueRegion) {
-        SkRect rect = SkRect::MakeXYWH(x, y, bitmap.width(), bitmap.height());
+    if (regionTrackingEnabled()) {
+        SkRect rect = SkRect::MakeXYWH(x, y, info.width(), info.height());
         SkPaint paint;
 
         paint.setXfermodeMode(SkXfermode::kSrc_Mode);
-        m_opaqueRegion.didDrawRect(this, rect, paint, &bitmap);
+        if (kOpaque_SkAlphaType != info.alphaType())
+            paint.setAlpha(0x80); // signal to m_trackedRegion that we are not fully opaque
+
+        m_trackedRegion.didDrawRect(this, rect, paint, 0);
+        // more efficient would be to call markRectAsOpaque or MarkRectAsNonOpaque directly,
+        // rather than cons-ing up a paint with an xfermode and alpha
     }
 }
 
 void GraphicsContext::drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top, const SkPaint* paint)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    // Textures are bound to the blink main-thread GrContext, which can not be
+    // used on the compositor raster thread.
+    // FIXME: Mailbox support would make this possible in the GPU-raster case.
+    ASSERT(!isRecording() || !bitmap.getTexture());
+    if (contextDisabled())
         return;
 
     m_canvas->drawBitmap(bitmap, left, top, paint);
 
-    if (m_trackOpaqueRegion) {
+    if (regionTrackingEnabled()) {
         SkRect rect = SkRect::MakeXYWH(left, top, bitmap.width(), bitmap.height());
-        m_opaqueRegion.didDrawRect(this, rect, *paint, &bitmap);
+        m_trackedRegion.didDrawRect(this, rect, *paint, &bitmap);
     }
 }
 
 void GraphicsContext::drawBitmapRect(const SkBitmap& bitmap, const SkRect* src,
     const SkRect& dst, const SkPaint* paint)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    // Textures are bound to the blink main-thread GrContext, which can not be
+    // used on the compositor raster thread.
+    // FIXME: Mailbox support would make this possible in the GPU-raster case.
+    ASSERT(!isRecording() || !bitmap.getTexture());
+    if (contextDisabled())
         return;
 
-    SkCanvas::DrawBitmapRectFlags flags = m_paintState->m_shouldClampToSourceRect ? SkCanvas::kNone_DrawBitmapRectFlag : SkCanvas::kBleed_DrawBitmapRectFlag;
+    SkCanvas::DrawBitmapRectFlags flags =
+        immutableState()->shouldClampToSourceRect() ? SkCanvas::kNone_DrawBitmapRectFlag : SkCanvas::kBleed_DrawBitmapRectFlag;
 
     m_canvas->drawBitmapRectToRect(bitmap, src, dst, paint, flags);
 
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawRect(this, dst, *paint, &bitmap);
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawRect(this, dst, *paint, &bitmap);
 }
 
 void GraphicsContext::drawOval(const SkRect& oval, const SkPaint& paint)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     m_canvas->drawOval(oval, paint);
 
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawBounded(this, oval, paint);
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawBounded(this, oval, paint);
 }
 
 void GraphicsContext::drawPath(const SkPath& path, const SkPaint& paint)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     m_canvas->drawPath(path, paint);
 
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawPath(this, path, paint);
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawPath(this, path, paint);
 }
 
 void GraphicsContext::drawRect(const SkRect& rect, const SkPaint& paint)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     m_canvas->drawRect(rect, paint);
 
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawRect(this, rect, paint, 0);
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawRect(this, rect, paint, 0);
+}
+
+void GraphicsContext::drawRRect(const SkRRect& rrect, const SkPaint& paint)
+{
+    ASSERT(m_canvas);
+    if (contextDisabled())
+        return;
+
+    m_canvas->drawRRect(rrect, paint);
+
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawBounded(this, rrect.rect(), paint);
 }
 
 void GraphicsContext::didDrawRect(const SkRect& rect, const SkPaint& paint, const SkBitmap* bitmap)
 {
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawRect(this, rect, paint, bitmap);
+    if (contextDisabled())
+        return;
+
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawRect(this, rect, paint, bitmap);
 }
 
 void GraphicsContext::drawPosText(const void* text, size_t byteLength,
-    const SkPoint pos[],  const SkRect& textRect, const SkPaint& paint)
+    const SkPoint pos[], const SkRect& textRect, const SkPaint& paint)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     m_canvas->drawPosText(text, byteLength, pos, paint);
     didDrawTextInRect(textRect);
 
     // FIXME: compute bounds for positioned text.
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawUnbounded(this, paint, OpaqueRegionSkia::FillOrStroke);
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawUnbounded(this, paint, RegionTracker::FillOrStroke);
 }
 
 void GraphicsContext::drawPosTextH(const void* text, size_t byteLength,
-    const SkScalar xpos[], SkScalar constY,  const SkRect& textRect, const SkPaint& paint)
+    const SkScalar xpos[], SkScalar constY, const SkRect& textRect, const SkPaint& paint)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     m_canvas->drawPosTextH(text, byteLength, xpos, constY, paint);
     didDrawTextInRect(textRect);
 
     // FIXME: compute bounds for positioned text.
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawUnbounded(this, paint, OpaqueRegionSkia::FillOrStroke);
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawUnbounded(this, paint, RegionTracker::FillOrStroke);
 }
 
-void GraphicsContext::drawTextOnPath(const void* text, size_t byteLength,
-    const SkPath& path,  const SkRect& textRect, const SkMatrix* matrix, const SkPaint& paint)
+void GraphicsContext::drawTextBlob(const SkTextBlob* blob, const SkPoint& origin, const SkPaint& paint)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
-    m_canvas->drawTextOnPath(text, byteLength, path, matrix, paint);
-    didDrawTextInRect(textRect);
+    m_canvas->drawTextBlob(blob, origin.x(), origin.y(), paint);
 
-    // FIXME: compute bounds for positioned text.
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawUnbounded(this, paint, OpaqueRegionSkia::FillOrStroke);
+    SkRect bounds = blob->bounds();
+    bounds.offset(origin);
+    didDrawTextInRect(bounds);
+
+    // FIXME: use bounds here if it helps performance.
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawUnbounded(this, paint, RegionTracker::FillOrStroke);
 }
 
 void GraphicsContext::fillPath(const Path& pathToFill)
 {
-    if (paintingDisabled() || pathToFill.isEmpty())
+    if (contextDisabled() || pathToFill.isEmpty())
         return;
 
     // Use const_cast and temporarily modify the fill type instead of copying the path.
     SkPath& path = const_cast<SkPath&>(pathToFill.skPath());
     SkPath::FillType previousFillType = path.getFillType();
 
-    SkPath::FillType temporaryFillType = m_paintState->m_fillRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType;
+    SkPath::FillType temporaryFillType = WebCoreWindRuleToSkFillType(immutableState()->fillRule());
     path.setFillType(temporaryFillType);
 
-    SkPaint paint;
-    setupPaintForFilling(&paint);
-    drawPath(path, paint);
+    drawPath(path, immutableState()->fillPaint());
 
     path.setFillType(previousFillType);
 }
 
 void GraphicsContext::fillRect(const FloatRect& rect)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     SkRect r = rect;
 
-    SkPaint paint;
-    setupPaintForFilling(&paint);
-    drawRect(r, paint);
+    drawRect(r, immutableState()->fillPaint());
 }
 
 void GraphicsContext::fillRect(const FloatRect& rect, const Color& color)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     SkRect r = rect;
-    SkPaint paint;
-    setupPaintCommon(&paint);
+    SkPaint paint = immutableState()->fillPaint();
     paint.setColor(color.rgb());
     drawRect(r, paint);
 }
 
+void GraphicsContext::fillBetweenRoundedRects(const IntRect& outer, const IntSize& outerTopLeft, const IntSize& outerTopRight, const IntSize& outerBottomLeft, const IntSize& outerBottomRight,
+    const IntRect& inner, const IntSize& innerTopLeft, const IntSize& innerTopRight, const IntSize& innerBottomLeft, const IntSize& innerBottomRight, const Color& color)
+{
+    ASSERT(m_canvas);
+    if (contextDisabled())
+        return;
+
+    SkVector outerRadii[4];
+    SkVector innerRadii[4];
+    setRadii(outerRadii, outerTopLeft, outerTopRight, outerBottomRight, outerBottomLeft);
+    setRadii(innerRadii, innerTopLeft, innerTopRight, innerBottomRight, innerBottomLeft);
+
+    SkRRect rrOuter;
+    SkRRect rrInner;
+    rrOuter.setRectRadii(outer, outerRadii);
+    rrInner.setRectRadii(inner, innerRadii);
+
+    SkPaint paint(immutableState()->fillPaint());
+    paint.setColor(color.rgb());
+
+    m_canvas->drawDRRect(rrOuter, rrInner, paint);
+
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawBounded(this, rrOuter.getBounds(), paint);
+}
+
+void GraphicsContext::fillBetweenRoundedRects(const RoundedRect& outer, const RoundedRect& inner, const Color& color)
+{
+    fillBetweenRoundedRects(outer.rect(), outer.radii().topLeft(), outer.radii().topRight(), outer.radii().bottomLeft(), outer.radii().bottomRight(),
+        inner.rect(), inner.radii().topLeft(), inner.radii().topRight(), inner.radii().bottomLeft(), inner.radii().bottomRight(), color);
+}
+
 void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight,
     const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     if (topLeft.width() + topRight.width() > rect.width()
@@ -1412,46 +1493,47 @@ void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLef
     SkRRect rr;
     rr.setRectRadii(rect, radii);
 
-    SkPaint paint;
-    setupPaintForFilling(&paint);
+    SkPaint paint(immutableState()->fillPaint());
     paint.setColor(color.rgb());
 
     m_canvas->drawRRect(rr, paint);
 
-    if (m_trackOpaqueRegion)
-        m_opaqueRegion.didDrawBounded(this, rr.getBounds(), paint);
+    if (regionTrackingEnabled())
+        m_trackedRegion.didDrawBounded(this, rr.getBounds(), paint);
 }
 
 void GraphicsContext::fillEllipse(const FloatRect& ellipse)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     SkRect rect = ellipse;
-    SkPaint paint;
-    setupPaintForFilling(&paint);
-    drawOval(rect, paint);
+    drawOval(rect, immutableState()->fillPaint());
 }
 
 void GraphicsContext::strokePath(const Path& pathToStroke)
 {
-    if (paintingDisabled() || pathToStroke.isEmpty())
+    if (contextDisabled() || pathToStroke.isEmpty())
         return;
 
     const SkPath& path = pathToStroke.skPath();
-    SkPaint paint;
-    setupPaintForStroking(&paint);
-    drawPath(path, paint);
+    drawPath(path, immutableState()->strokePaint());
+}
+
+void GraphicsContext::strokeRect(const FloatRect& rect)
+{
+    strokeRect(rect, strokeThickness());
 }
 
 void GraphicsContext::strokeRect(const FloatRect& rect, float lineWidth)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    SkPaint paint;
-    setupPaintForStroking(&paint);
+    SkPaint paint(immutableState()->strokePaint());
     paint.setStrokeWidth(WebCoreFloatToSkScalar(lineWidth));
+    // Reset the dash effect to account for the width
+    immutableState()->strokeData().setupPaintDashPathEffect(&paint, 0);
     // strokerect has special rules for CSS when the rect is degenerate:
     // if width==0 && height==0, do nothing
     // if width==0 || height==0, then just draw line for the other dimension
@@ -1473,20 +1555,22 @@ void GraphicsContext::strokeRect(const FloatRect& rect, float lineWidth)
 
 void GraphicsContext::strokeEllipse(const FloatRect& ellipse)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    SkRect rect(ellipse);
-    SkPaint paint;
-    setupPaintForStroking(&paint);
-    drawOval(rect, paint);
+    drawOval(ellipse, immutableState()->strokePaint());
 }
 
-void GraphicsContext::clipRoundedRect(const RoundedRect& rect)
+void GraphicsContext::clipRoundedRect(const RoundedRect& rect, SkRegion::Op regionOp)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
+    if (!rect.isRounded()) {
+        clipRect(rect.rect(), NotAntiAliased, regionOp);
+        return;
+    }
+
     SkVector radii[4];
     RoundedRect::Radii wkRadii = rect.radii();
     setRadii(radii, wkRadii.topLeft(), wkRadii.topRight(), wkRadii.bottomRight(), wkRadii.bottomLeft());
@@ -1494,12 +1578,12 @@ void GraphicsContext::clipRoundedRect(const RoundedRect& rect)
     SkRRect r;
     r.setRectRadii(rect.rect(), radii);
 
-    clipRRect(r, AntiAliased);
+    clipRRect(r, AntiAliased, regionOp);
 }
 
 void GraphicsContext::clipOut(const Path& pathToClip)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     // Use const_cast and temporarily toggle the inverse fill type instead of copying the path.
@@ -1511,133 +1595,138 @@ void GraphicsContext::clipOut(const Path& pathToClip)
 
 void GraphicsContext::clipPath(const Path& pathToClip, WindRule clipRule)
 {
-    if (paintingDisabled() || pathToClip.isEmpty())
+    if (contextDisabled() || pathToClip.isEmpty())
         return;
 
     // Use const_cast and temporarily modify the fill type instead of copying the path.
     SkPath& path = const_cast<SkPath&>(pathToClip.skPath());
     SkPath::FillType previousFillType = path.getFillType();
 
-    SkPath::FillType temporaryFillType = clipRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType;
+    SkPath::FillType temporaryFillType = WebCoreWindRuleToSkFillType(clipRule);
     path.setFillType(temporaryFillType);
     clipPath(path, AntiAliased);
 
     path.setFillType(previousFillType);
 }
 
-void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased)
+void GraphicsContext::clipPolygon(size_t numPoints, const FloatPoint* points, bool antialiased)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
-    if (numPoints <= 1)
-        return;
+    ASSERT(numPoints > 2);
 
     SkPath path;
-    setPathFromConvexPoints(&path, numPoints, points);
+    setPathFromPoints(&path, numPoints, points);
     clipPath(path, antialiased ? AntiAliased : NotAntiAliased);
 }
 
 void GraphicsContext::clipOutRoundedRect(const RoundedRect& rect)
 {
-    if (paintingDisabled())
-        return;
-
-    if (!rect.isRounded()) {
-        clipOut(rect.rect());
+    if (contextDisabled())
         return;
-    }
 
-    Path path;
-    path.addRoundedRect(rect);
-    clipOut(path);
+    clipRoundedRect(rect, SkRegion::kDifference_Op);
 }
 
-void GraphicsContext::canvasClip(const Path& pathToClip, WindRule clipRule)
+void GraphicsContext::canvasClip(const Path& pathToClip, WindRule clipRule, AntiAliasingMode aa)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     // Use const_cast and temporarily modify the fill type instead of copying the path.
     SkPath& path = const_cast<SkPath&>(pathToClip.skPath());
     SkPath::FillType previousFillType = path.getFillType();
 
-    SkPath::FillType temporaryFillType = clipRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType;
+    SkPath::FillType temporaryFillType = WebCoreWindRuleToSkFillType(clipRule);
     path.setFillType(temporaryFillType);
-    clipPath(path);
+    clipPath(path, aa);
 
     path.setFillType(previousFillType);
 }
 
-bool GraphicsContext::clipRect(const SkRect& rect, AntiAliasingMode aa, SkRegion::Op op)
+void GraphicsContext::clipRect(const SkRect& rect, AntiAliasingMode aa, SkRegion::Op op)
 {
-    if (paintingDisabled())
-        return false;
-
-    realizeCanvasSave(SkCanvas::kClip_SaveFlag);
+    ASSERT(m_canvas);
+    if (contextDisabled())
+        return;
 
-    return m_canvas->clipRect(rect, op, aa == AntiAliased);
+    m_canvas->clipRect(rect, op, aa == AntiAliased);
 }
 
-bool GraphicsContext::clipPath(const SkPath& path, AntiAliasingMode aa, SkRegion::Op op)
+void GraphicsContext::clipPath(const SkPath& path, AntiAliasingMode aa, SkRegion::Op op)
 {
-    if (paintingDisabled())
-        return false;
+    ASSERT(m_canvas);
+    if (contextDisabled())
+        return;
 
-    realizeCanvasSave(SkCanvas::kClip_SaveFlag);
+    m_canvas->clipPath(path, op, aa == AntiAliased);
+}
+
+void GraphicsContext::clipRRect(const SkRRect& rect, AntiAliasingMode aa, SkRegion::Op op)
+{
+    ASSERT(m_canvas);
+    if (contextDisabled())
+        return;
 
-    return m_canvas->clipPath(path, op, aa == AntiAliased);
+    m_canvas->clipRRect(rect, op, aa == AntiAliased);
 }
 
-bool GraphicsContext::clipRRect(const SkRRect& rect, AntiAliasingMode aa, SkRegion::Op op)
+void GraphicsContext::beginCull(const FloatRect& rect)
 {
-    if (paintingDisabled())
-        return false;
+    ASSERT(m_canvas);
+    if (contextDisabled())
+        return;
+
+    m_canvas->pushCull(rect);
+}
 
-    realizeCanvasSave(SkCanvas::kClip_SaveFlag);
+void GraphicsContext::endCull()
+{
+    ASSERT(m_canvas);
+    if (contextDisabled())
+        return;
 
-    return m_canvas->clipRRect(rect, op, aa == AntiAliased);
+    m_canvas->popCull();
 }
 
 void GraphicsContext::rotate(float angleInRadians)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
-    realizeCanvasSave(SkCanvas::kMatrix_SaveFlag);
-
     m_canvas->rotate(WebCoreFloatToSkScalar(angleInRadians * (180.0f / 3.14159265f)));
 }
 
-void GraphicsContext::translate(float w, float h)
+void GraphicsContext::translate(float x, float y)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
-    if (!w && !h)
+    if (!x && !y)
         return;
 
-    realizeCanvasSave(SkCanvas::kMatrix_SaveFlag);
-
-    m_canvas->translate(WebCoreFloatToSkScalar(w), WebCoreFloatToSkScalar(h));
+    m_canvas->translate(WebCoreFloatToSkScalar(x), WebCoreFloatToSkScalar(y));
 }
 
-void GraphicsContext::scale(const FloatSize& size)
+void GraphicsContext::scale(float x, float y)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
-    if (size.width() == 1.0f && size.height() == 1.0f)
+    if (x == 1.0f && y == 1.0f)
         return;
 
-    realizeCanvasSave(SkCanvas::kMatrix_SaveFlag);
-
-    m_canvas->scale(WebCoreFloatToSkScalar(size.width()), WebCoreFloatToSkScalar(size.height()));
+    m_canvas->scale(WebCoreFloatToSkScalar(x), WebCoreFloatToSkScalar(y));
 }
 
 void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     SkAutoDataUnref url(SkData::NewWithCString(link.string().utf8().data()));
@@ -1646,7 +1735,8 @@ void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect)
 
 void GraphicsContext::setURLFragmentForRect(const String& destName, const IntRect& rect)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     SkAutoDataUnref skDestName(SkData::NewWithCString(destName.utf8().data()));
@@ -1655,16 +1745,17 @@ void GraphicsContext::setURLFragmentForRect(const String& destName, const IntRec
 
 void GraphicsContext::addURLTargetAtPoint(const String& name, const IntPoint& pos)
 {
-    if (paintingDisabled())
+    ASSERT(m_canvas);
+    if (contextDisabled())
         return;
 
     SkAutoDataUnref nameData(SkData::NewWithCString(name.utf8().data()));
     SkAnnotateNamedDestination(m_canvas, SkPoint::Make(pos.x(), pos.y()), nameData);
 }
 
-AffineTransform GraphicsContext::getCTM(IncludeDeviceScale) const
+AffineTransform GraphicsContext::getCTM() const
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return AffineTransform();
 
     SkMatrix m = getTotalMatrix();
@@ -1678,7 +1769,7 @@ AffineTransform GraphicsContext::getCTM(IncludeDeviceScale) const
 
 void GraphicsContext::fillRect(const FloatRect& rect, const Color& color, CompositeOperator op)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     CompositeOperator previousOperator = compositeOperation();
@@ -1689,6 +1780,9 @@ void GraphicsContext::fillRect(const FloatRect& rect, const Color& color, Compos
 
 void GraphicsContext::fillRoundedRect(const RoundedRect& rect, const Color& color)
 {
+    if (contextDisabled())
+        return;
+
     if (rect.isRounded())
         fillRoundedRect(rect.rect(), rect.radii().topLeft(), rect.radii().topRight(), rect.radii().bottomLeft(), rect.radii().bottomRight(), color);
     else
@@ -1697,7 +1791,7 @@ void GraphicsContext::fillRoundedRect(const RoundedRect& rect, const Color& colo
 
 void GraphicsContext::fillRectWithRoundedHole(const IntRect& rect, const RoundedRect& roundedHoleRect, const Color& color)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     Path path;
@@ -1722,12 +1816,11 @@ void GraphicsContext::fillRectWithRoundedHole(const IntRect& rect, const Rounded
 
 void GraphicsContext::clearRect(const FloatRect& rect)
 {
-    if (paintingDisabled())
+    if (contextDisabled())
         return;
 
     SkRect r = rect;
-    SkPaint paint;
-    setupPaintForFilling(&paint);
+    SkPaint paint(immutableState()->fillPaint());
     paint.setXfermodeMode(SkXfermode::kClear_Mode);
     drawRect(r, paint);
 }
@@ -1761,58 +1854,27 @@ void GraphicsContext::adjustLineToPixelBoundaries(FloatPoint& p1, FloatPoint& p2
     }
 }
 
-PassOwnPtr<ImageBuffer> GraphicsContext::createCompatibleBuffer(const IntSize& size, OpacityMode opacityMode) const
+PassOwnPtr<ImageBuffer> GraphicsContext::createRasterBuffer(const IntSize& size, OpacityMode opacityMode) const
 {
     // Make the buffer larger if the context's transform is scaling it so we need a higher
     // resolution than one pixel per unit. Also set up a corresponding scale factor on the
     // graphics context.
 
-    AffineTransform transform = getCTM(DefinitelyIncludeDeviceScale);
+    AffineTransform transform = getCTM();
     IntSize scaledSize(static_cast<int>(ceil(size.width() * transform.xScale())), static_cast<int>(ceil(size.height() * transform.yScale())));
 
-    RefPtr<SkBaseDevice> device = adoptRef(m_canvas->getTopDevice()->createCompatibleDevice(SkBitmap::kARGB_8888_Config, size.width(), size.height(), opacityMode == Opaque));
-    if (!device)
+    OwnPtr<ImageBufferSurface> surface = adoptPtr(new UnacceleratedImageBufferSurface(scaledSize, opacityMode));
+    if (!surface->isValid())
         return nullptr;
-    OwnPtr<ImageBufferSurface> surface = adoptPtr(new CompatibleImageBufferSurface(device.release(), scaledSize, opacityMode));
-    ASSERT(surface->isValid());
     OwnPtr<ImageBuffer> buffer = adoptPtr(new ImageBuffer(surface.release()));
 
-    buffer->context()->scale(FloatSize(static_cast<float>(scaledSize.width()) / size.width(),
-        static_cast<float>(scaledSize.height()) / size.height()));
+    buffer->context()->scale(static_cast<float>(scaledSize.width()) / size.width(),
+        static_cast<float>(scaledSize.height()) / size.height());
 
     return buffer.release();
 }
 
-void GraphicsContext::addCornerArc(SkPath* path, const SkRect& rect, const IntSize& size, int startAngle)
-{
-    SkIRect ir;
-    int rx = SkMin32(SkScalarRoundToInt(rect.width()), size.width());
-    int ry = SkMin32(SkScalarRoundToInt(rect.height()), size.height());
-
-    ir.set(-rx, -ry, rx, ry);
-    switch (startAngle) {
-    case 0:
-        ir.offset(rect.fRight - ir.fRight, rect.fBottom - ir.fBottom);
-        break;
-    case 90:
-        ir.offset(rect.fLeft - ir.fLeft, rect.fBottom - ir.fBottom);
-        break;
-    case 180:
-        ir.offset(rect.fLeft - ir.fLeft, rect.fTop - ir.fTop);
-        break;
-    case 270:
-        ir.offset(rect.fRight - ir.fRight, rect.fTop - ir.fTop);
-        break;
-    default:
-        ASSERT(0);
-    }
-
-    SkRect r;
-    r.set(ir);
-    path->arcTo(r, SkIntToScalar(startAngle), SkIntToScalar(90), false);
-}
-
-void GraphicsContext::setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points)
+void GraphicsContext::setPathFromPoints(SkPath* path, size_t numPoints, const FloatPoint* points)
 {
     path->incReserve(numPoints);
     path->moveTo(WebCoreFloatToSkScalar(points[0].x()),
@@ -1821,59 +1883,6 @@ void GraphicsContext::setPathFromConvexPoints(SkPath* path, size_t numPoints, co
         path->lineTo(WebCoreFloatToSkScalar(points[i].x()),
                      WebCoreFloatToSkScalar(points[i].y()));
     }
-
-    /*  The code used to just blindly call this
-            path->setIsConvex(true);
-        But webkit can sometimes send us non-convex 4-point values, so we mark the path's
-        convexity as unknown, so it will get computed by skia at draw time.
-        See crbug.com 108605
-    */
-    SkPath::Convexity convexity = SkPath::kConvex_Convexity;
-    if (numPoints == 4)
-        convexity = SkPath::kUnknown_Convexity;
-    path->setConvexity(convexity);
-}
-
-void GraphicsContext::setupPaintCommon(SkPaint* paint) const
-{
-#if defined(SK_DEBUG)
-    {
-        SkPaint defaultPaint;
-        SkASSERT(*paint == defaultPaint);
-    }
-#endif
-
-    paint->setAntiAlias(m_paintState->m_shouldAntialias);
-
-    if (!SkXfermode::IsMode(m_paintState->m_xferMode.get(), SkXfermode::kSrcOver_Mode))
-        paint->setXfermode(m_paintState->m_xferMode.get());
-
-    if (m_paintState->m_looper)
-        paint->setLooper(m_paintState->m_looper.get());
-
-    paint->setColorFilter(m_paintState->m_colorFilter.get());
-}
-
-void GraphicsContext::drawOuterPath(const SkPath& path, SkPaint& paint, int width)
-{
-#if OS(MACOSX)
-    paint.setAlpha(64);
-    paint.setStrokeWidth(width);
-    paint.setPathEffect(new SkCornerPathEffect((width - 1) * 0.5f))->unref();
-#else
-    paint.setStrokeWidth(1);
-    paint.setPathEffect(new SkCornerPathEffect(1))->unref();
-#endif
-    drawPath(path, paint);
-}
-
-void GraphicsContext::drawInnerPath(const SkPath& path, SkPaint& paint, int width)
-{
-#if OS(MACOSX)
-    paint.setAlpha(128);
-    paint.setStrokeWidth(width * 0.5f);
-    drawPath(path, paint);
-#endif
 }
 
 void GraphicsContext::setRadii(SkVector* radii, IntSize topLeft, IntSize topRight, IntSize bottomRight, IntSize bottomLeft)
@@ -1904,16 +1913,10 @@ PassRefPtr<SkColorFilter> GraphicsContext::WebCoreColorFilterToSkiaColorFilter(C
         break;
     }
 
-    return 0;
+    return nullptr;
 }
 
-#if OS(MACOSX)
-CGColorSpaceRef PLATFORM_EXPORT deviceRGBColorSpaceRef()
-{
-    static CGColorSpaceRef deviceSpace = CGColorSpaceCreateDeviceRGB();
-    return deviceSpace;
-}
-#else
+#if !OS(MACOSX)
 void GraphicsContext::draw2xMarker(SkBitmap* bitmap, int index)
 {
     const SkPMColor lineColor = lineColors(index);
@@ -1974,7 +1977,7 @@ void GraphicsContext::draw1xMarker(SkBitmap* bitmap, int index)
     }
 }
 
-const SkPMColor GraphicsContext::lineColors(int index)
+SkPMColor GraphicsContext::lineColors(int index)
 {
     static const SkPMColor colors[] = {
         SkPreMultiplyARGB(0xFF, 0xFF, 0x00, 0x00), // Opaque red.
@@ -1984,7 +1987,7 @@ const SkPMColor GraphicsContext::lineColors(int index)
     return colors[index];
 }
 
-const SkPMColor GraphicsContext::antiColors1(int index)
+SkPMColor GraphicsContext::antiColors1(int index)
 {
     static const SkPMColor colors[] = {
         SkPreMultiplyARGB(0xB0, 0xFF, 0x00, 0x00), // Semitransparent red.
@@ -1994,7 +1997,7 @@ const SkPMColor GraphicsContext::antiColors1(int index)
     return colors[index];
 }
 
-const SkPMColor GraphicsContext::antiColors2(int index)
+SkPMColor GraphicsContext::antiColors2(int index)
 {
     static const SkPMColor colors[] = {
         SkPreMultiplyARGB(0x60, 0xFF, 0x00, 0x00), // More transparent red
@@ -2005,33 +2008,62 @@ const SkPMColor GraphicsContext::antiColors2(int index)
 }
 #endif
 
-void GraphicsContext::setupShader(SkPaint* paint, Gradient* grad, Pattern* pat, SkColor color) const
-{
-    RefPtr<SkShader> shader;
-
-    if (grad) {
-        shader = grad->shader();
-        color = SK_ColorBLACK;
-    } else if (pat) {
-        shader = pat->shader();
-        color = SK_ColorBLACK;
-        paint->setFilterBitmap(imageInterpolationQuality() != InterpolationNone);
-    }
-
-    paint->setColor(m_paintState->applyAlpha(color));
-
-    if (!shader)
-        return;
-
-    paint->setShader(shader.get());
-}
-
 void GraphicsContext::didDrawTextInRect(const SkRect& textRect)
 {
     if (m_trackTextRegion) {
-        TRACE_EVENT0("skia", "PlatformContextSkia::trackTextRegion");
+        TRACE_EVENT0("skia", "GraphicsContext::didDrawTextInRect");
         m_textRegion.join(textRect);
     }
 }
 
+void GraphicsContext::preparePaintForDrawRectToRect(
+    SkPaint* paint,
+    const SkRect& srcRect,
+    const SkRect& destRect,
+    CompositeOperator compositeOp,
+    WebBlendMode blendMode,
+    bool isBitmapWithAlpha,
+    bool isLazyDecoded,
+    bool isDataComplete) const
+{
+    paint->setXfermodeMode(WebCoreCompositeToSkiaComposite(compositeOp, blendMode));
+    paint->setColorFilter(this->colorFilter());
+    paint->setAlpha(this->getNormalizedAlpha());
+    if (this->dropShadowImageFilter() && isBitmapWithAlpha) {
+        paint->setImageFilter(this->dropShadowImageFilter());
+    } else {
+        paint->setLooper(this->drawLooper());
+    }
+    paint->setAntiAlias(shouldDrawAntiAliased(this, destRect));
+
+    InterpolationQuality resampling;
+    if (this->isAccelerated()) {
+        resampling = InterpolationLow;
+    } else if (this->printing()) {
+        resampling = InterpolationNone;
+    } else if (isLazyDecoded) {
+        resampling = InterpolationHigh;
+    } else {
+        // Take into account scale applied to the canvas when computing sampling mode (e.g. CSS scale or page scale).
+        SkRect destRectTarget = destRect;
+        SkMatrix totalMatrix = this->getTotalMatrix();
+        if (!(totalMatrix.getType() & (SkMatrix::kAffine_Mask | SkMatrix::kPerspective_Mask)))
+            totalMatrix.mapRect(&destRectTarget, destRect);
+
+        resampling = computeInterpolationQuality(totalMatrix,
+            SkScalarToFloat(srcRect.width()), SkScalarToFloat(srcRect.height()),
+            SkScalarToFloat(destRectTarget.width()), SkScalarToFloat(destRectTarget.height()),
+            isDataComplete);
+    }
+
+    if (resampling == InterpolationNone) {
+        // FIXME: This is to not break tests (it results in the filter bitmap flag
+        // being set to true). We need to decide if we respect InterpolationNone
+        // being returned from computeInterpolationQuality.
+        resampling = InterpolationLow;
+    }
+    resampling = limitInterpolationQuality(this, resampling);
+    paint->setFilterLevel(static_cast<SkPaint::FilterLevel>(resampling));
 }
+
+} // namespace blink