Merge from Chromium at DEPS revision r205460

This commit was generated by merge_to_master.py.

Change-Id: Id50fcfa40590db3bd322348190cb5192c432eadf
diff --git a/Source/core/rendering/EllipsisBox.cpp b/Source/core/rendering/EllipsisBox.cpp
index 5028535..a0d570c 100644
--- a/Source/core/rendering/EllipsisBox.cpp
+++ b/Source/core/rendering/EllipsisBox.cpp
@@ -39,7 +39,7 @@
     RenderStyle* style = m_renderer->style(isFirstLineStyle());
     Color styleTextColor = style->visitedDependentColor(CSSPropertyWebkitTextFillColor);
     if (styleTextColor != context->fillColor())
-        context->setFillColor(styleTextColor, style->colorSpace());
+        context->setFillColor(styleTextColor);
 
     Color textColor = styleTextColor;
     const Font& font = style->font();
@@ -49,7 +49,7 @@
         // Select the correct color for painting the text.
         Color foreground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionForegroundColor();
         if (foreground.isValid() && foreground != styleTextColor)
-            context->setFillColor(foreground, style->colorSpace());
+            context->setFillColor(foreground);
     }
 
     const ShadowData* shadow = style->textShadow();
@@ -79,7 +79,7 @@
 
     // Restore the regular fill color.
     if (styleTextColor != context->fillColor())
-        context->setFillColor(styleTextColor, style->colorSpace());
+        context->setFillColor(styleTextColor);
 
     if (hasShadow)
         context->clearDrawLooper();
@@ -145,7 +145,7 @@
     alignSelectionRectToDevicePixels(clipRect);
     context->clip(clipRect);
     // FIXME: Why is this always LTR? Fix by passing correct text run flags below.
-    context->drawHighlightForText(font, RenderBlock::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), roundedIntPoint(LayoutPoint(x() + paintOffset.x(), y() + paintOffset.y() + top)), h, c, style->colorSpace());
+    context->drawHighlightForText(font, RenderBlock::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), roundedIntPoint(LayoutPoint(x() + paintOffset.x(), y() + paintOffset.y() + top)), h, c);
 }
 
 bool EllipsisBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
diff --git a/Source/core/rendering/FilterEffectRenderer.cpp b/Source/core/rendering/FilterEffectRenderer.cpp
index d3f6e07..38a8fe0 100644
--- a/Source/core/rendering/FilterEffectRenderer.cpp
+++ b/Source/core/rendering/FilterEffectRenderer.cpp
@@ -29,6 +29,7 @@
 #include "core/rendering/FilterEffectRenderer.h"
 
 #include "SVGNames.h"
+#include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/dom/Document.h"
 #include "core/loader/cache/CachedDocument.h"
 #include "core/loader/cache/CachedSVGDocumentReference.h"
@@ -89,6 +90,46 @@
         operation->meshRows(), operation->meshColumns(),  operation->meshType());
 }
 
+// Returns whether or not the SVGStyledElement object contains a valid color-interpolation-filters attribute
+static bool getSVGStyledElementColorSpace(SVGStyledElement* svgStyledElement, ColorSpace& cs)
+{
+    if (!svgStyledElement)
+        return false;
+
+    const RenderObject* renderer = svgStyledElement->renderer();
+    const RenderStyle* style = renderer ? renderer->style() : 0;
+    const SVGRenderStyle* svgStyle = style ? style->svgStyle() : 0;
+    EColorInterpolation eColorInterpolation = CI_AUTO;
+    if (svgStyle) {
+        // If a layout has been performed, then we can use the fast path to get this attribute
+        eColorInterpolation = svgStyle->colorInterpolationFilters();
+    } else {
+        // Otherwise, use the slow path by using string comparison (used by external svg files)
+        RefPtr<CSSValue> cssValue = svgStyledElement->getPresentationAttribute(
+            SVGNames::color_interpolation_filtersAttr.toString());
+        if (cssValue.get() && cssValue->isPrimitiveValue()) {
+            const CSSPrimitiveValue& primitiveValue = *((CSSPrimitiveValue*)cssValue.get());
+            eColorInterpolation = (EColorInterpolation)primitiveValue;
+        } else {
+            return false;
+        }
+    }
+
+    switch (eColorInterpolation) {
+    case CI_AUTO:
+    case CI_SRGB:
+        cs = ColorSpaceDeviceRGB;
+        break;
+    case CI_LINEARRGB:
+        cs = ColorSpaceLinearRGB;
+        break;
+    default:
+        return false;
+    }
+
+    return true;
+}
+
 FilterEffectRenderer::FilterEffectRenderer()
     : Filter(AffineTransform())
     , m_graphicsBufferAttached(false)
@@ -149,6 +190,9 @@
     // This may need a spec clarification.
     RefPtr<SVGFilterBuilder> builder = SVGFilterBuilder::create(previousEffect, SourceAlpha::create(this));
 
+    ColorSpace filterColorSpace = ColorSpaceDeviceRGB;
+    const bool useFilterColorSpace = getSVGStyledElementColorSpace(filterElement, filterColorSpace);
+
     for (Node* node = filterElement->firstChild(); node; node = node->nextSibling()) {
         if (!node->isSVGElement())
             continue;
@@ -165,6 +209,10 @@
 
         effectElement->setStandardAttributes(effect.get());
         effect->setEffectBoundaries(SVGLengthContext::resolveRectangle<SVGFilterPrimitiveStandardAttributes>(effectElement, filterElement->primitiveUnits(), sourceImageRect()));
+
+        ColorSpace colorSpace = filterColorSpace;
+        if (useFilterColorSpace || getSVGStyledElementColorSpace(effectElement, colorSpace))
+            effect->setOperatingColorSpace(colorSpace);
         builder->add(effectElement->result(), effect);
         m_effects.append(effect);
     }
@@ -341,11 +389,10 @@
         }
 
         if (effect) {
-            effect->setOperatingColorSpace(ColorSpaceDeviceRGB);
-            
             if (filterOperation->getOperationType() != FilterOperation::REFERENCE) {
                 // Unlike SVG, filters applied here should not clip to their primitive subregions.
                 effect->setClipsToBounds(false);
+                effect->setOperatingColorSpace(ColorSpaceDeviceRGB);
                 effect->inputEffects().append(previousEffect);
                 m_effects.append(effect);
             }
@@ -380,7 +427,7 @@
     if (!m_graphicsBufferAttached) {
         IntSize logicalSize(m_sourceDrawingRegion.width(), m_sourceDrawingRegion.height());
         if (!sourceImage() || sourceImage()->logicalSize() != logicalSize)
-            setSourceImage(ImageBuffer::create(logicalSize, 1, ColorSpaceDeviceRGB, renderingMode()));
+            setSourceImage(ImageBuffer::create(logicalSize, 1, renderingMode()));
         m_graphicsBufferAttached = true;
     }
 }
@@ -486,12 +533,12 @@
     filter->inputContext()->restore();
 
     filter->apply();
-    
+
     // Get the filtered output and draw it in place.
-    m_savedGraphicsContext->drawImageBuffer(filter->output(), m_renderLayer->renderer()->style()->colorSpace(), filter->outputRect(), CompositeSourceOver);
-    
+    m_savedGraphicsContext->drawImageBuffer(filter->output(), filter->outputRect(), CompositeSourceOver);
+
     filter->clearIntermediateResults();
-    
+
     return m_savedGraphicsContext;
 }
 
diff --git a/Source/core/rendering/HitTestResult.cpp b/Source/core/rendering/HitTestResult.cpp
index 384e6dd..07163ac 100644
--- a/Source/core/rendering/HitTestResult.cpp
+++ b/Source/core/rendering/HitTestResult.cpp
@@ -245,7 +245,7 @@
     }
     
     if (m_innerNonSharedNode->hasTagName(inputTag)) {
-        HTMLInputElement* input = static_cast<HTMLInputElement*>(m_innerNonSharedNode.get());
+        HTMLInputElement* input = toHTMLInputElement(m_innerNonSharedNode.get());
         return displayString(input->alt(), m_innerNonSharedNode.get());
     }
 
@@ -347,6 +347,17 @@
     return false;
 }
 
+bool HitTestResult::isMisspelled() const
+{
+    if (!targetNode())
+        return false;
+    VisiblePosition pos(targetNode()->renderer()->positionForPoint(localPoint()));
+    if (pos.isNull())
+        return false;
+    return m_innerNonSharedNode->document()->markers()->markersInRange(
+        makeRange(pos, pos).get(), DocumentMarker::Spelling | DocumentMarker::Grammar).size() > 0;
+}
+
 String HitTestResult::titleDisplayString() const
 {
     if (!m_innerURLElement)
@@ -375,7 +386,7 @@
         return true;
 
     if (m_innerNonSharedNode->hasTagName(inputTag))
-        return static_cast<HTMLInputElement*>(m_innerNonSharedNode.get())->isTextField();
+        return toHTMLInputElement(m_innerNonSharedNode.get())->isTextField();
 
     return m_innerNonSharedNode->rendererIsEditable();
 }
diff --git a/Source/core/rendering/HitTestResult.h b/Source/core/rendering/HitTestResult.h
index e613614..63347ca 100644
--- a/Source/core/rendering/HitTestResult.h
+++ b/Source/core/rendering/HitTestResult.h
@@ -104,6 +104,7 @@
     KURL absoluteLinkURL() const;
     String textContent() const;
     bool isLiveLink() const;
+    bool isMisspelled() const;
     bool isContentEditable() const;
 
     // Returns true if it is rect-based hit test and needs to continue until the rect is fully
diff --git a/Source/core/rendering/InlineBox.h b/Source/core/rendering/InlineBox.h
index eb97253..a7025cf 100644
--- a/Source/core/rendering/InlineBox.h
+++ b/Source/core/rendering/InlineBox.h
@@ -277,7 +277,7 @@
 
     int expansion() const { return m_bitfields.expansion(); }
 
-    bool visibleToHitTestRequest(const HitTestRequest& request) const { return renderer()->style()->visibility() == VISIBLE && (request.ignorePointerEventsNone() || renderer()->style()->pointerEvents() != PE_NONE); }
+    bool visibleToHitTestRequest(const HitTestRequest& request) const { return renderer()->visibleToHitTestRequest(request); }
     
     EVerticalAlign verticalAlign() const { return renderer()->style(m_bitfields.firstLine())->verticalAlign(); }
 
diff --git a/Source/core/rendering/InlineTextBox.cpp b/Source/core/rendering/InlineTextBox.cpp
index a1a2eff..381320e 100644
--- a/Source/core/rendering/InlineTextBox.cpp
+++ b/Source/core/rendering/InlineTextBox.cpp
@@ -350,7 +350,7 @@
     return textColor.light();
 }
 
-void updateGraphicsContext(GraphicsContext* context, const Color& fillColor, const Color& strokeColor, float strokeThickness, ColorSpace colorSpace)
+void updateGraphicsContext(GraphicsContext* context, const Color& fillColor, const Color& strokeColor, float strokeThickness)
 {
     TextDrawingModeFlags mode = context->textDrawingMode();
     if (strokeThickness > 0) {
@@ -360,13 +360,13 @@
             mode = newMode;
         }
     }
-    
-    if (mode & TextModeFill && (fillColor != context->fillColor() || colorSpace != context->fillColorSpace()))
-        context->setFillColor(fillColor, colorSpace);
+
+    if (mode & TextModeFill && fillColor != context->fillColor())
+        context->setFillColor(fillColor);
 
     if (mode & TextModeStroke) {
         if (strokeColor != context->strokeColor())
-            context->setStrokeColor(strokeColor, colorSpace);
+            context->setStrokeColor(strokeColor);
         if (strokeThickness != context->strokeThickness())
             context->setStrokeThickness(strokeThickness);
     }
@@ -393,33 +393,6 @@
     return false;
 }
 
-FloatSize InlineTextBox::applyShadowToGraphicsContext(GraphicsContext* context, const ShadowData* shadow, const FloatRect& textRect, bool stroked, bool opaque, bool horizontal)
-{
-    if (!shadow)
-        return FloatSize();
-
-    FloatSize extraOffset;
-    int shadowX = horizontal ? shadow->x() : shadow->y();
-    int shadowY = horizontal ? shadow->y() : -shadow->x();
-    FloatSize shadowOffset(shadowX, shadowY);
-    int shadowBlur = shadow->blur();
-    const Color& shadowColor = shadow->color();
-
-    if (shadow->next() || stroked || !opaque) {
-        FloatRect shadowRect(textRect);
-        shadowRect.inflate(shadowBlur);
-        shadowRect.move(shadowOffset);
-        context->save();
-        context->clip(shadowRect);
-
-        extraOffset = FloatSize(0, 2 * textRect.height() + max(0.0f, shadowOffset.height()) + shadowBlur);
-        shadowOffset -= extraOffset;
-    }
-
-    context->setShadow(shadowOffset, shadowBlur, shadowColor);
-    return extraOffset;
-}
-
 static void paintTextWithShadows(GraphicsContext* context, const Font& font, const TextRun& textRun,
                                  const AtomicString& emphasisMark, int emphasisMarkOffset,
                                  int startOffset, int endOffset, int truncationPoint,
@@ -737,7 +710,7 @@
         // effect, so only when we know we're stroking, do a save/restore.
         GraphicsContextStateSaver stateSaver(*context, textStrokeWidth > 0);
 
-        updateGraphicsContext(context, textFillColor, textStrokeColor, textStrokeWidth, styleToUse->colorSpace());
+        updateGraphicsContext(context, textFillColor, textStrokeColor, textStrokeWidth);
         if (!paintSelectedTextSeparately || ePos <= sPos) {
             // FIXME: Truncate right-to-left text correctly.
             paintTextWithShadows(context, font, textRun, nullAtom, 0, 0, length, length, textOrigin, boxRect, textShadow, textStrokeWidth > 0, isHorizontal());
@@ -745,7 +718,7 @@
             paintTextWithShadows(context, font, textRun, nullAtom, 0, ePos, sPos, length, textOrigin, boxRect, textShadow, textStrokeWidth > 0, isHorizontal());
 
         if (!emphasisMark.isEmpty()) {
-            updateGraphicsContext(context, emphasisMarkColor, textStrokeColor, textStrokeWidth, styleToUse->colorSpace());
+            updateGraphicsContext(context, emphasisMarkColor, textStrokeColor, textStrokeWidth);
 
             DEFINE_STATIC_LOCAL(TextRun, objectReplacementCharacterTextRun, (&objectReplacementCharacter, 1));
             TextRun& emphasisMarkTextRun = combinedText ? objectReplacementCharacterTextRun : textRun;
@@ -768,10 +741,10 @@
         // paint only the text that is selected
         GraphicsContextStateSaver stateSaver(*context, selectionStrokeWidth > 0);
 
-        updateGraphicsContext(context, selectionFillColor, selectionStrokeColor, selectionStrokeWidth, styleToUse->colorSpace());
+        updateGraphicsContext(context, selectionFillColor, selectionStrokeColor, selectionStrokeWidth);
         paintTextWithShadows(context, font, textRun, nullAtom, 0, sPos, ePos, length, textOrigin, boxRect, selectionShadow, selectionStrokeWidth > 0, isHorizontal());
         if (!emphasisMark.isEmpty()) {
-            updateGraphicsContext(context, selectionEmphasisMarkColor, textStrokeColor, textStrokeWidth, styleToUse->colorSpace());
+            updateGraphicsContext(context, selectionEmphasisMarkColor, textStrokeColor, textStrokeWidth);
 
             DEFINE_STATIC_LOCAL(TextRun, objectReplacementCharacterTextRun, (&objectReplacementCharacter, 1));
             TextRun& emphasisMarkTextRun = combinedText ? objectReplacementCharacterTextRun : textRun;
@@ -789,7 +762,7 @@
     // Paint decorations
     TextDecoration textDecorations = styleToUse->textDecorationsInEffect();
     if (textDecorations != TextDecorationNone && paintInfo.phase != PaintPhaseSelection) {
-        updateGraphicsContext(context, textFillColor, textStrokeColor, textStrokeWidth, styleToUse->colorSpace());
+        updateGraphicsContext(context, textFillColor, textStrokeColor, textStrokeWidth);
         if (combinedText)
             context->concatCTM(rotation(boxRect, Clockwise));
         paintDecoration(context, boxOrigin, textDecorations, styleToUse->textDecorationStyle(), textShadow);
@@ -876,8 +849,8 @@
         c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
 
     GraphicsContextStateSaver stateSaver(*context);
-    updateGraphicsContext(context, c, c, 0, style->colorSpace());  // Don't draw text at all!
-    
+    updateGraphicsContext(context, c, c, 0); // Don't draw text at all!
+
     // If the text is truncated, let the thing being painted in the truncation
     // draw its own highlight.
     int length = m_truncation != cNoTruncation ? m_truncation : m_len;
@@ -906,7 +879,7 @@
 
     context->clip(clipRect);
 
-    context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
+    context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, sPos, ePos);
 }
 
 void InlineTextBox::paintCompositionBackground(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, int startPos, int endPos)
@@ -921,13 +894,13 @@
     GraphicsContextStateSaver stateSaver(*context);
 
     Color c = Color(225, 221, 85);
-    
-    updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
+
+    updateGraphicsContext(context, c, c, 0); // Don't draw text at all!
 
     int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
     int selHeight = selectionHeight();
     FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
-    context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
+    context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, sPos, ePos);
 }
 
 static StrokeStyle textDecorationStyleToStrokeStyle(TextDecorationStyle decorationStyle)
@@ -937,7 +910,6 @@
     case TextDecorationStyleSolid:
         strokeStyle = SolidStroke;
         break;
-#if ENABLE(CSS3_TEXT)
     case TextDecorationStyleDouble:
         strokeStyle = DoubleStroke;
         break;
@@ -950,7 +922,6 @@
     case TextDecorationStyleWavy:
         strokeStyle = WavyStroke;
         break;
-#endif // CSS3_TEXT
     }
 
     return strokeStyle;
@@ -983,7 +954,6 @@
 }
 #endif // CSS3_TEXT
 
-#if ENABLE(CSS3_TEXT)
 static void adjustStepToDecorationLength(float& step, float& controlPointDistance, float length)
 {
     ASSERT(step > 0);
@@ -1105,7 +1075,6 @@
     context->setShouldAntialias(true);
     context->strokePath(path);
 }
-#endif // CSS3_TEXT
 
 void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, TextDecoration deco, TextDecorationStyle decorationStyle, const ShadowData* shadow)
 {
@@ -1158,8 +1127,6 @@
         localOrigin.move(0, extraOffset);
     }
 
-    ColorSpace colorSpace = renderer()->style()->colorSpace();
-
     do {
         if (shadow) {
             if (!shadow->next()) {
@@ -1173,16 +1140,17 @@
             shadow = shadow->next();
         }
 
-#if ENABLE(CSS3_TEXT)
         // Offset between lines - always non-zero, so lines never cross each other.
         float doubleOffset = textDecorationThickness + 1.f;
-#endif // CSS3_TEXT
         context->setStrokeStyle(textDecorationStyleToStrokeStyle(decorationStyle));
         if (deco & TextDecorationUnderline) {
-            context->setStrokeColor(underline, colorSpace);
+            context->setStrokeColor(underline);
 #if ENABLE(CSS3_TEXT)
             TextUnderlinePosition underlinePosition = styleToUse->textUnderlinePosition();
             const int underlineOffset = computeUnderlineOffset(underlinePosition, styleToUse->fontMetrics(), this, textDecorationThickness);
+#else
+            const int underlineOffset = styleToUse->fontMetrics().ascent() + max<int>(1, ceilf(textDecorationThickness / 2.0));
+#endif // CSS3_TEXT
 
             switch (decorationStyle) {
             case TextDecorationStyleWavy: {
@@ -1197,14 +1165,9 @@
                 if (decorationStyle == TextDecorationStyleDouble)
                     context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + underlineOffset + doubleOffset), width, isPrinting);
             }
-#else
-            // Leave one pixel of white between the baseline and the underline.
-            context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + baseline + 1), width, isPrinting);
-#endif // CSS3_TEXT
         }
         if (deco & TextDecorationOverline) {
-            context->setStrokeColor(overline, colorSpace);
-#if ENABLE(CSS3_TEXT)
+            context->setStrokeColor(overline);
             switch (decorationStyle) {
             case TextDecorationStyleWavy: {
                 FloatPoint start(localOrigin.x(), localOrigin.y() - doubleOffset);
@@ -1213,17 +1176,13 @@
                 break;
             }
             default:
-#endif // CSS3_TEXT
                 context->drawLineForText(localOrigin, width, isPrinting);
-#if ENABLE(CSS3_TEXT)
                 if (decorationStyle == TextDecorationStyleDouble)
                     context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() - doubleOffset), width, isPrinting);
             }
-#endif // CSS3_TEXT
         }
         if (deco & TextDecorationLineThrough) {
-            context->setStrokeColor(linethrough, colorSpace);
-#if ENABLE(CSS3_TEXT)
+            context->setStrokeColor(linethrough);
             switch (decorationStyle) {
             case TextDecorationStyleWavy: {
                 FloatPoint start(localOrigin.x(), localOrigin.y() + 2 * baseline / 3);
@@ -1232,13 +1191,10 @@
                 break;
             }
             default:
-#endif // CSS3_TEXT
                 context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + 2 * baseline / 3), width, isPrinting);
-#if ENABLE(CSS3_TEXT)
                 if (decorationStyle == TextDecorationStyleDouble)
                     context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + doubleOffset + 2 * baseline / 3), width, isPrinting);
             }
-#endif // CSS3_TEXT
         }
     } while (shadow);
 }
@@ -1339,16 +1295,16 @@
     IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, IntPoint(x(), selectionTop()), selHeight, sPos, ePos));
     markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
     toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
-    
+
     // Optionally highlight the text
     if (renderer()->frame()->editor()->markedTextMatchesAreHighlighted()) {
         Color color = marker->activeMatch() ?
             renderer()->theme()->platformActiveTextSearchHighlightColor() :
             renderer()->theme()->platformInactiveTextSearchHighlightColor();
         GraphicsContextStateSaver stateSaver(*pt);
-        updateGraphicsContext(pt, color, color, 0, style->colorSpace());  // Don't draw text at all!
+        updateGraphicsContext(pt, color, color, 0); // Don't draw text at all!
         pt->clip(FloatRect(boxOrigin.x(), boxOrigin.y() - deltaY, m_logicalWidth, selHeight));
-        pt->drawHighlightForText(font, run, FloatPoint(boxOrigin.x(), boxOrigin.y() - deltaY), selHeight, color, style->colorSpace(), sPos, ePos);
+        pt->drawHighlightForText(font, run, FloatPoint(boxOrigin.x(), boxOrigin.y() - deltaY), selHeight, color, sPos, ePos);
     }
 }
 
@@ -1447,7 +1403,7 @@
     start += 1;
     width -= 2;
 
-    ctx->setStrokeColor(underline.color, renderer()->style()->colorSpace());
+    ctx->setStrokeColor(underline.color);
     ctx->setStrokeThickness(lineThickness);
     ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, textRenderer()->document()->printing());
 }
diff --git a/Source/core/rendering/InlineTextBox.h b/Source/core/rendering/InlineTextBox.h
index 2fb6355..5d05b4e 100644
--- a/Source/core/rendering/InlineTextBox.h
+++ b/Source/core/rendering/InlineTextBox.h
@@ -164,9 +164,6 @@
 
     bool containsCaretOffset(int offset) const; // false for offset after line break
 
-    // Needs to be public, so the static paintTextWithShadows() function can use it.
-    static FloatSize applyShadowToGraphicsContext(GraphicsContext*, const ShadowData*, const FloatRect& textRect, bool stroked, bool opaque, bool horizontal);
-
 private:
     InlineTextBox* m_prevTextBox; // The previous box that also uses our RenderObject
     InlineTextBox* m_nextTextBox; // The next box that also uses our RenderObject
diff --git a/Source/core/rendering/RenderBlock.cpp b/Source/core/rendering/RenderBlock.cpp
index 9658b29..bb94740 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -2449,7 +2449,7 @@
 {
     // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
     // an auto value. Add a method to determine this, so that we can avoid the relayout.
-    if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()) || child->hasViewportPercentageLogicalHeight())
+    if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()))
         child->setChildNeedsLayout(true, MarkOnlyThis);
 
     // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
@@ -2889,6 +2889,8 @@
  
 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     LayoutPoint adjustedPaintOffset = paintOffset + location();
     
     PaintPhase phase = paintInfo.phase;
@@ -3626,7 +3628,7 @@
 
     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
     if (paintInfo)
-        paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selectionBackgroundColor(), style()->colorSpace());
+        paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selectionBackgroundColor());
     return gapRect;
 }
 
@@ -3642,7 +3644,7 @@
 
     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
     if (paintInfo)
-        paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
+        paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selObj->selectionBackgroundColor());
     return gapRect;
 }
 
@@ -3658,7 +3660,7 @@
 
     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
     if (paintInfo)
-        paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
+        paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selObj->selectionBackgroundColor());
     return gapRect;
 }
 
@@ -4752,7 +4754,7 @@
 
 void RenderBlock::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
 {
-    if (!everHadLayout())
+    if (!everHadLayout() && !containsFloats())
         return;
 
     MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
@@ -6064,11 +6066,10 @@
                 }
 
                 // Add in text-indent.  This is added in only once.
-                LayoutUnit ti = 0;
                 if (!addedTextIndent && !child->isFloating()) {
-                    ti = textIndent;
-                    childMin += ti.ceilToFloat();
-                    childMax += ti.ceilToFloat();
+                    float ceiledTextIndent = textIndent.ceilToFloat();
+                    childMin += ceiledTextIndent;
+                    childMax += ceiledTextIndent;
 
                     if (childMin < 0)
                         textIndent = adjustFloatForSubPixelLayout(childMin);
diff --git a/Source/core/rendering/RenderBlockLineLayout.cpp b/Source/core/rendering/RenderBlockLineLayout.cpp
index fccfa31..fe6872d 100644
--- a/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -119,7 +119,7 @@
     void applyOverhang(RenderRubyRun*, RenderObject* startRenderer, RenderObject* endRenderer);
     void fitBelowFloats();
 
-    bool shouldIndentText() { return m_shouldIndentText == IndentText; }
+    bool shouldIndentText() const { return m_shouldIndentText == IndentText; }
 
 private:
     void computeAvailableWidthFromLeftAndRight()
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index 5b40ce9..3e0bca6 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -271,7 +271,7 @@
     }
 
     // Our opaqueness might have changed without triggering layout.
-    if (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer) {
+    if (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintIfText || diff == StyleDifferenceRepaintLayer) {
         RenderObject* parentToInvalidate = parent();
         for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
             parentToInvalidate->invalidateBackgroundObscurationStatus();
@@ -715,6 +715,11 @@
         layer()->autoscroll(position);
 }
 
+bool RenderBox::autoscrollInProgress() const
+{
+    return frame() && frame()->page() && frame()->page()->autoscrollInProgress(this);
+}
+
 // There are two kinds of renderer that can autoscroll.
 bool RenderBox::canAutoscroll() const
 {
@@ -1774,7 +1779,11 @@
 
 LayoutSize RenderBox::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
 {
-    ASSERT(o == container());
+    // A region "has" boxes inside it without being their container.
+    // FIXME: change container() / containingBlock() to count for boxes being positioned relative to the region, not the
+    // FlowThread. This requires a separate patch as a simple test with such a change in container() causes 129 out of
+    // 337 regions tests to fail.
+    ASSERT(o == container() || o->isRenderRegion());
 
     LayoutSize offset;    
     if (hasPaintOffset())
@@ -2212,7 +2221,7 @@
     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
     // block-flow (as well as how marquee overflow should relate to block flow).
     // https://bugs.webkit.org/show_bug.cgi?id=46472
-    if (parent()->style()->overflowX() == OMARQUEE) {
+    if (parent()->isHTMLMarquee()) {
         EMarqueeDirection dir = parent()->style()->marqueeDirection();
         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
             return true;
@@ -2263,6 +2272,16 @@
         return;
     }
 
+    if (containingBlock->isFlexibleBox()) {
+        // We need to let flexbox handle the margin adjustment - otherwise, flexbox
+        // will think we're wider than we actually are and calculate line sizes wrong.
+        // See also http://dev.w3.org/csswg/css-flexbox/#auto-margins
+        if (marginStartLength.isAuto())
+            marginStartLength.setValue(0);
+        if (marginEndLength.isAuto())
+            marginEndLength.setValue(0);
+    }
+
     // Case One: The object is being centered in the containing block's available logical width.
     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style()->textAlign() == WEBKIT_CENTER)) {
@@ -4510,21 +4529,18 @@
 
 bool RenderBox::hasRelativeDimensions() const
 {
+    // FIXME: This should probably include viewport percentage heights as well.
     return style()->height().isPercent() || style()->width().isPercent()
-            || style()->maxHeight().isPercent() || style()->maxWidth().isPercent()
-            || style()->minHeight().isPercent() || style()->minWidth().isPercent();
+        || style()->maxHeight().isPercent() || style()->maxWidth().isPercent()
+        || style()->minHeight().isPercent() || style()->minWidth().isPercent();
 }
 
 bool RenderBox::hasRelativeLogicalHeight() const
 {
     return style()->logicalHeight().isPercent()
-            || style()->logicalMinHeight().isPercent()
-            || style()->logicalMaxHeight().isPercent();
-}
-
-bool RenderBox::hasViewportPercentageLogicalHeight() const
-{
-    return style()->logicalHeight().isViewportPercentage()
+        || style()->logicalMinHeight().isPercent()
+        || style()->logicalMaxHeight().isPercent()
+        || style()->logicalHeight().isViewportPercentage()
         || style()->logicalMinHeight().isViewportPercentage()
         || style()->logicalMaxHeight().isViewportPercentage();
 }
diff --git a/Source/core/rendering/RenderBox.h b/Source/core/rendering/RenderBox.h
index bce0122..045cde1 100644
--- a/Source/core/rendering/RenderBox.h
+++ b/Source/core/rendering/RenderBox.h
@@ -49,7 +49,7 @@
     // position:static elements that are not flex-items get their z-index coerced to auto.
     virtual bool requiresLayer() const OVERRIDE { return isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasOverflowClip() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns() || !style()->hasAutoZIndex() || isFloatingWithShapeOutside(); }
 
-    virtual bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const OVERRIDE FINAL;
+    virtual bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const OVERRIDE;
 
     // Use this with caution! No type checking is done!
     RenderBox* firstChildBox() const;
@@ -443,6 +443,7 @@
     bool canBeScrolledAndHasScrollableArea() const;
     virtual bool canBeProgramaticallyScrolled() const;
     virtual void autoscroll(const IntPoint&);
+    bool autoscrollInProgress() const;
     bool canAutoscroll() const;
     IntSize calculateAutoscrollDirection(const IntPoint& windowPoint) const;
     static RenderBox* findAutoscrollable(RenderObject*);
@@ -543,7 +544,6 @@
 
     virtual bool hasRelativeDimensions() const;
     virtual bool hasRelativeLogicalHeight() const;
-    bool hasViewportPercentageLogicalHeight() const;
 
     bool hasHorizontalLayoutOverflow() const
     {
diff --git a/Source/core/rendering/RenderBoxModelObject.cpp b/Source/core/rendering/RenderBoxModelObject.cpp
index 98d59b6..a8ec0f9 100644
--- a/Source/core/rendering/RenderBoxModelObject.cpp
+++ b/Source/core/rendering/RenderBoxModelObject.cpp
@@ -573,7 +573,7 @@
     }
 
     bool colorVisible = bgColor.isValid() && bgColor.alpha();
-    
+
     // Fast path for drawing simple color backgrounds.
     if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
         if (!colorVisible)
@@ -587,16 +587,17 @@
         if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
             RoundedRect border = backgroundRoundedRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge);
             if (border.isRenderable())
-                context->fillRoundedRect(border, bgColor, style()->colorSpace());
+                context->fillRoundedRect(border, bgColor);
             else {
                 context->save();
                 clipRoundedInnerRect(context, rect, border);
-                context->fillRect(border.rect(), bgColor, style()->colorSpace());
+                context->fillRect(border.rect(), bgColor);
                 context->restore();
             }
-        } else
-            context->fillRect(pixelSnappedIntRect(rect), bgColor, style()->colorSpace());
-        
+        } else {
+            context->fillRect(pixelSnappedIntRect(rect), bgColor);
+        }
+
         return;
     }
 
@@ -731,10 +732,10 @@
                 if (bgColor.alpha())
                     baseColor = baseColor.blend(bgColor);
 
-                context->fillRect(backgroundRect, baseColor, style()->colorSpace(), CompositeCopy);
+                context->fillRect(backgroundRect, baseColor, CompositeCopy);
             } else if (bgColor.alpha()) {
                 CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
-                context->fillRect(backgroundRect, bgColor, style()->colorSpace(), operation);
+                context->fillRect(backgroundRect, bgColor, operation);
             } else if (shouldClearBackground)
                 context->clearRect(backgroundRect);
         }
@@ -750,7 +751,7 @@
             RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
             RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
             bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
-            context->drawTiledImage(image.get(), style()->colorSpace(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(), 
+            context->drawTiledImage(image.get(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(),
                 compositeOp, useLowQualityScaling, bgLayer->blendMode());
         }
     }
@@ -1140,7 +1141,7 @@
     int rightWidth = computeBorderImageSide(ninePieceImage.borderSlices().right(), style->borderRightWidth(), rightSlice, borderImageRect.width(), renderView);
     int bottomWidth = computeBorderImageSide(ninePieceImage.borderSlices().bottom(), style->borderBottomWidth(), bottomSlice, borderImageRect.height(), renderView);
     int leftWidth = computeBorderImageSide(ninePieceImage.borderSlices().left(), style->borderLeftWidth(), leftSlice, borderImageRect.width(), renderView);
-    
+
     // Reduce the widths if they're too large.
     // The spec says: Given Lwidth as the width of the border image area, Lheight as its height, and Wside as the border image width
     // offset for the side, let f = min(Lwidth/(Wleft+Wright), Lheight/(Wtop+Wbottom)). If f < 1, then all W are reduced by
@@ -1163,39 +1164,37 @@
                       && (imageHeight - topSlice - bottomSlice) > 0 && (borderImageRect.height() - topWidth - bottomWidth) > 0;
 
     RefPtr<Image> image = styleImage->image(this, imageSize);
-    ColorSpace colorSpace = style->colorSpace();
-    
+
     float destinationWidth = borderImageRect.width() - leftWidth - rightWidth;
     float destinationHeight = borderImageRect.height() - topWidth - bottomWidth;
-    
+
     float sourceWidth = imageWidth - leftSlice - rightSlice;
     float sourceHeight = imageHeight - topSlice - bottomSlice;
-    
+
     float leftSideScale = drawLeft ? (float)leftWidth / leftSlice : 1;
     float rightSideScale = drawRight ? (float)rightWidth / rightSlice : 1;
     float topSideScale = drawTop ? (float)topWidth / topSlice : 1;
     float bottomSideScale = drawBottom ? (float)bottomWidth / bottomSlice : 1;
-    
+
     if (drawLeft) {
         // Paint the top and bottom left corners.
 
         // The top left corner rect is (tx, ty, leftWidth, topWidth)
         // The rect to use from within the image is obtained from our slice, and is (0, 0, leftSlice, topSlice)
         if (drawTop)
-            graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.location(), IntSize(leftWidth, topWidth)),
+            graphicsContext->drawImage(image.get(), IntRect(borderImageRect.location(), IntSize(leftWidth, topWidth)),
                                        LayoutRect(0, 0, leftSlice, topSlice), op);
 
         // The bottom left corner rect is (tx, ty + h - bottomWidth, leftWidth, bottomWidth)
         // The rect to use from within the image is (0, imageHeight - bottomSlice, leftSlice, botomSlice)
         if (drawBottom)
-            graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.x(), borderImageRect.maxY() - bottomWidth, leftWidth, bottomWidth),
+            graphicsContext->drawImage(image.get(), IntRect(borderImageRect.x(), borderImageRect.maxY() - bottomWidth, leftWidth, bottomWidth),
                                        LayoutRect(0, imageHeight - bottomSlice, leftSlice, bottomSlice), op);
 
         // Paint the left edge.
         // Have to scale and tile into the border rect.
         if (sourceHeight > 0)
-            graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x(), borderImageRect.y() + topWidth, leftWidth,
-                                            destinationHeight),
+            graphicsContext->drawTiledImage(image.get(), IntRect(borderImageRect.x(), borderImageRect.y() + topWidth, leftWidth, destinationHeight),
                                             IntRect(0, topSlice, leftSlice, sourceHeight),
                                             FloatSize(leftSideScale, leftSideScale), Image::StretchTile, (Image::TileRule)vRule, op);
     }
@@ -1205,18 +1204,18 @@
         // The top right corner rect is (tx + w - rightWidth, ty, rightWidth, topWidth)
         // The rect to use from within the image is obtained from our slice, and is (imageWidth - rightSlice, 0, rightSlice, topSlice)
         if (drawTop)
-            graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y(), rightWidth, topWidth),
+            graphicsContext->drawImage(image.get(), IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y(), rightWidth, topWidth),
                                        LayoutRect(imageWidth - rightSlice, 0, rightSlice, topSlice), op);
 
         // The bottom right corner rect is (tx + w - rightWidth, ty + h - bottomWidth, rightWidth, bottomWidth)
         // The rect to use from within the image is (imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice)
         if (drawBottom)
-            graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.maxY() - bottomWidth, rightWidth, bottomWidth),
+            graphicsContext->drawImage(image.get(), IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.maxY() - bottomWidth, rightWidth, bottomWidth),
                                        LayoutRect(imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice), op);
 
         // Paint the right edge.
         if (sourceHeight > 0)
-            graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y() + topWidth, rightWidth,
+            graphicsContext->drawTiledImage(image.get(), IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y() + topWidth, rightWidth,
                                             destinationHeight),
                                             IntRect(imageWidth - rightSlice, topSlice, rightSlice, sourceHeight),
                                             FloatSize(rightSideScale, rightSideScale),
@@ -1225,13 +1224,13 @@
 
     // Paint the top edge.
     if (drawTop && sourceWidth > 0)
-        graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.y(), destinationWidth, topWidth),
+        graphicsContext->drawTiledImage(image.get(), IntRect(borderImageRect.x() + leftWidth, borderImageRect.y(), destinationWidth, topWidth),
                                         IntRect(leftSlice, 0, sourceWidth, topSlice),
                                         FloatSize(topSideScale, topSideScale), (Image::TileRule)hRule, Image::StretchTile, op);
 
     // Paint the bottom edge.
     if (drawBottom && sourceWidth > 0)
-        graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.maxY() - bottomWidth,
+        graphicsContext->drawTiledImage(image.get(), IntRect(borderImageRect.x() + leftWidth, borderImageRect.maxY() - bottomWidth,
                                         destinationWidth, bottomWidth),
                                         IntRect(leftSlice, imageHeight - bottomSlice, sourceWidth, bottomSlice),
                                         FloatSize(bottomSideScale, bottomSideScale),
@@ -1248,18 +1247,18 @@
             middleScaleFactor.setHeight(leftSideScale);
         else if (drawRight)
             middleScaleFactor.setHeight(rightSideScale);
-            
+
         // For "stretch" rules, just override the scale factor and replace. We only had to do this for the
         // center tile, since sides don't even use the scale factor unless they have a rule other than "stretch".
         // The middle however can have "stretch" specified in one axis but not the other, so we have to
         // correct the scale here.
         if (hRule == StretchImageRule)
             middleScaleFactor.setWidth(destinationWidth / sourceWidth);
-            
+
         if (vRule == StretchImageRule)
             middleScaleFactor.setHeight(destinationHeight / sourceHeight);
-        
-        graphicsContext->drawTiledImage(image.get(), colorSpace,
+
+        graphicsContext->drawTiledImage(image.get(),
             IntRect(borderImageRect.x() + leftWidth, borderImageRect.y() + topWidth, destinationWidth, destinationHeight),
             IntRect(leftSlice, topSlice, sourceWidth, sourceHeight),
             middleScaleFactor, (Image::TileRule)hRule, (Image::TileRule)vRule, op);
@@ -1796,7 +1795,7 @@
                 path.addRect(innerBorder.rect());
             
             graphicsContext->setFillRule(RULE_EVENODD);
-            graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
+            graphicsContext->setFillColor(edges[firstVisibleEdge].color);
             graphicsContext->fillPath(path);
             return;
         } 
@@ -1813,7 +1812,7 @@
             }
 
             graphicsContext->setFillRule(RULE_NONZERO);
-            graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
+            graphicsContext->setFillColor(edges[firstVisibleEdge].color);
             graphicsContext->fillPath(path);
             return;
         }
@@ -1842,8 +1841,8 @@
 }
 
 void RenderBoxModelObject::drawBoxSideFromPath(GraphicsContext* graphicsContext, const LayoutRect& borderRect, const Path& borderPath, const BorderEdge edges[],
-                                    float thickness, float drawThickness, BoxSide side, const RenderStyle* style, 
-                                    Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
+    float thickness, float drawThickness, BoxSide side, const RenderStyle* style, Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance,
+    bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
 {
     if (thickness <= 0)
         return;
@@ -1857,7 +1856,7 @@
         return;
     case DOTTED:
     case DASHED: {
-        graphicsContext->setStrokeColor(color, style->colorSpace());
+        graphicsContext->setStrokeColor(color);
 
         // The stroke is doubled here because the provided path is the 
         // outside edge of the border so half the stroke is clipped off. 
@@ -1989,7 +1988,7 @@
     }
 
     graphicsContext->setStrokeStyle(NoStroke);
-    graphicsContext->setFillColor(color, style->colorSpace());
+    graphicsContext->setFillColor(color);
     graphicsContext->drawRect(pixelSnappedIntRect(borderRect));
 }
 
@@ -2367,6 +2366,7 @@
     bool isHorizontal = s->isHorizontalWritingMode();
     
     bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
+    bool contextWasClipped = false;
     for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
         if (shadow->style() != shadowStyle)
             continue;
@@ -2390,8 +2390,6 @@
             shadowRect.inflate(shadowBlur + shadowSpread);
             shadowRect.move(shadowOffset);
 
-            GraphicsContextStateSaver stateSaver(*context);
-
             // Draw only the shadow.
             DrawLooper drawLooper;
             drawLooper.addShadow(shadowOffset, shadowBlur, shadowColor,
@@ -2399,46 +2397,55 @@
             context->setDrawLooper(drawLooper);
 
             if (hasBorderRadius) {
-                RoundedRect rectToClipOut = border;
+                if (!contextWasClipped) {
+                    RoundedRect rectToClipOut = border;
 
-                // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
-                // when painting the shadow. On the other hand, it introduces subpixel gaps along the
-                // corners. Those are avoided by insetting the clipping path by one pixel.
-                if (hasOpaqueBackground) {
-                    rectToClipOut.inflateWithRadii(-1);
+                    // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
+                    // when painting the shadow. On the other hand, it introduces subpixel gaps along the
+                    // corners. Those are avoided by insetting the clipping path by one pixel.
+                    if (hasOpaqueBackground)
+                        rectToClipOut.inflateWithRadii(-1);
+
+                    if (!rectToClipOut.isEmpty()) {
+                        context->save();
+                        context->clipOutRoundedRect(rectToClipOut);
+                        contextWasClipped = true;
+                    }
                 }
 
-                if (!rectToClipOut.isEmpty())
-                    context->clipOutRoundedRect(rectToClipOut);
-
                 RoundedRect influenceRect(shadowRect, border.radii());
                 influenceRect.expandRadii(2 * shadowBlur + shadowSpread);
                 if (allCornersClippedOut(influenceRect, info.rect))
-                    context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
+                    context->fillRect(fillRect.rect(), Color::black);
                 else {
                     fillRect.expandRadii(shadowSpread);
                     if (!fillRect.isRenderable())
                         fillRect.adjustRadii();
-                    context->fillRoundedRect(fillRect, Color::black, s->colorSpace());
+                    context->fillRoundedRect(fillRect, Color::black);
                 }
             } else {
-                IntRect rectToClipOut = border.rect();
+                if (!contextWasClipped) {
+                    IntRect rectToClipOut = border.rect();
 
-                // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
-                // when painting the shadow. On the other hand, it introduces subpixel gaps along the
-                // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
-                // by one pixel.
-                if (hasOpaqueBackground) {
-                    // FIXME: The function to decide on the policy based on the transform should be a named function.
-                    // FIXME: It's not clear if this check is right. What about integral scale factors?
-                    AffineTransform transform = context->getCTM();
-                    if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
-                        rectToClipOut.inflate(-1);
+                    // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
+                    // when painting the shadow. On the other hand, it introduces subpixel gaps along the
+                    // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
+                    // by one pixel.
+                    if (hasOpaqueBackground) {
+                        // FIXME: The function to decide on the policy based on the transform should be a named function.
+                        // FIXME: It's not clear if this check is right. What about integral scale factors?
+                        AffineTransform transform = context->getCTM();
+                        if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
+                            rectToClipOut.inflate(-1);
+                    }
+
+                    if (!rectToClipOut.isEmpty()) {
+                        context->save();
+                        context->clipOut(rectToClipOut);
+                        contextWasClipped = true;
+                    }
                 }
-
-                if (!rectToClipOut.isEmpty())
-                    context->clipOut(rectToClipOut);
-                context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
+                context->fillRect(fillRect.rect(), Color::black);
             }
         } else {
             // Inset shadow.
@@ -2447,9 +2454,9 @@
 
             if (holeRect.isEmpty()) {
                 if (hasBorderRadius)
-                    context->fillRoundedRect(border, shadowColor, s->colorSpace());
+                    context->fillRoundedRect(border, shadowColor);
                 else
-                    context->fillRect(border.rect(), shadowColor, s->colorSpace());
+                    context->fillRect(border.rect(), shadowColor);
                 continue;
             }
 
@@ -2473,23 +2480,32 @@
 
             IntRect outerRect = areaCastingShadowInHole(border.rect(), shadowBlur, shadowSpread, shadowOffset);
             RoundedRect roundedHole(holeRect, border.radii());
-
-            GraphicsContextStateSaver stateSaver(*context);
-            if (hasBorderRadius) {
-                Path path;
-                path.addRoundedRect(border);
-                context->clipPath(path);
+            if (hasBorderRadius)
                 roundedHole.shrinkRadii(shadowSpread);
-            } else
-                context->clip(border.rect());
+
+            if (!contextWasClipped) {
+                context->save();
+                if (hasBorderRadius) {
+                    Path path;
+                    path.addRoundedRect(border);
+                    context->clipPath(path);
+                } else {
+                    context->clip(border.rect());
+                }
+                contextWasClipped = true;
+            }
 
             DrawLooper drawLooper;
             drawLooper.addShadow(shadowOffset, shadowBlur, shadowColor,
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
             context->setDrawLooper(drawLooper);
-            context->fillRectWithRoundedHole(outerRect, roundedHole, fillColor, s->colorSpace());
+            context->fillRectWithRoundedHole(outerRect, roundedHole, fillColor);
         }
     }
+
+    if (contextWasClipped)
+        context->restore();
+    context->clearDrawLooper();
 }
 
 LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const
@@ -2615,6 +2631,19 @@
     if (!o)
         return;
 
+    // The point inside a box that's inside a region has its coordinates relative to the region,
+    // not the FlowThread that is its container in the RenderObject tree.
+    if (o->isRenderFlowThread() && isRenderBlock()) {
+        // FIXME: switch to Box instead of Block when we'll have range information for boxes as well, not just for blocks.
+        RenderRegion* startRegion;
+        RenderRegion* ignoredEndRegion;
+        toRenderFlowThread(o)->getRegionRangeForBox(toRenderBlock(this), startRegion, ignoredEndRegion);
+        // If there is no region to use the FlowThread, then there's no region range for the content in that FlowThread.
+        // An API like elementFromPoint might crash without this check.
+        if (startRegion)
+            o = startRegion;
+    }
+
     o->mapAbsoluteToLocalPoint(mode, transformState);
 
     LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint());
diff --git a/Source/core/rendering/RenderButton.cpp b/Source/core/rendering/RenderButton.cpp
index 3ba55d4..5398661 100644
--- a/Source/core/rendering/RenderButton.cpp
+++ b/Source/core/rendering/RenderButton.cpp
@@ -109,7 +109,7 @@
 {
     // If we're an input element, we may need to change our button text.
     if (node()->hasTagName(inputTag)) {
-        HTMLInputElement* input = static_cast<HTMLInputElement*>(node());
+        HTMLInputElement* input = toHTMLInputElement(node());
         String value = input->valueWithDefault();
         setText(value);
     }
diff --git a/Source/core/rendering/RenderDetailsMarker.cpp b/Source/core/rendering/RenderDetailsMarker.cpp
index 0b8c299..308defb 100644
--- a/Source/core/rendering/RenderDetailsMarker.cpp
+++ b/Source/core/rendering/RenderDetailsMarker.cpp
@@ -127,10 +127,10 @@
         return;
 
     const Color color(style()->visitedDependentColor(CSSPropertyColor));
-    paintInfo.context->setStrokeColor(color, style()->colorSpace());
+    paintInfo.context->setStrokeColor(color);
     paintInfo.context->setStrokeStyle(SolidStroke);
     paintInfo.context->setStrokeThickness(1.0f);
-    paintInfo.context->setFillColor(color, style()->colorSpace());
+    paintInfo.context->setFillColor(color);
 
     boxOrigin.move(borderLeft() + paddingLeft(), borderTop() + paddingTop());
     paintInfo.context->fillPath(getPath(boxOrigin));
diff --git a/Source/core/rendering/RenderEmbeddedObject.cpp b/Source/core/rendering/RenderEmbeddedObject.cpp
index 2727615..700d8ab 100644
--- a/Source/core/rendering/RenderEmbeddedObject.cpp
+++ b/Source/core/rendering/RenderEmbeddedObject.cpp
@@ -163,7 +163,7 @@
     GraphicsContextStateSaver stateSaver(*context);
     context->clip(contentRect);
     context->setAlpha(replacementTextRoundedRectOpacity);
-    context->setFillColor(Color::white, style()->colorSpace());
+    context->setFillColor(Color::white);
     context->fillPath(path);
 
     const FontMetrics& fontMetrics = font.fontMetrics();
@@ -172,7 +172,7 @@
     TextRunPaintInfo runInfo(run);
     runInfo.bounds = replacementTextRect;
     context->setAlpha(replacementTextTextOpacity);
-    context->setFillColor(Color::black, style()->colorSpace());
+    context->setFillColor(Color::black);
     context->drawBidiText(font, runInfo, FloatPoint(labelX, labelY));
 }
 
diff --git a/Source/core/rendering/RenderFileUploadControl.cpp b/Source/core/rendering/RenderFileUploadControl.cpp
index e25a9cf..596e6c6 100644
--- a/Source/core/rendering/RenderFileUploadControl.cpp
+++ b/Source/core/rendering/RenderFileUploadControl.cpp
@@ -66,7 +66,7 @@
 
 void RenderFileUploadControl::updateFromElement()
 {
-    HTMLInputElement* input = static_cast<HTMLInputElement*>(node());
+    HTMLInputElement* input = toHTMLInputElement(node());
     ASSERT(input->isFileUpload());
 
     if (HTMLInputElement* button = uploadButton()) {
@@ -92,7 +92,7 @@
 
 int RenderFileUploadControl::maxFilenameWidth() const
 {
-    HTMLInputElement* input = static_cast<HTMLInputElement*>(node());
+    HTMLInputElement* input = toHTMLInputElement(node());
     return max(0, contentBoxRect().pixelSnappedWidth() - nodeWidth(uploadButton()) - afterButtonSpacing
         - (input->icon() ? iconWidth + iconFilenameSpacing : 0));
 }
@@ -125,7 +125,7 @@
         if (!button)
             return;
 
-        HTMLInputElement* input = static_cast<HTMLInputElement*>(node());
+        HTMLInputElement* input = toHTMLInputElement(node());
         LayoutUnit buttonWidth = nodeWidth(button);
         LayoutUnit buttonAndIconWidth = buttonWidth + afterButtonSpacing
             + (input->icon() ? iconWidth + iconFilenameSpacing : 0);
@@ -149,11 +149,11 @@
                                             textWidth,
                                             style()->fontMetrics().height());
 
-        paintInfo.context->setFillColor(style()->visitedDependentColor(CSSPropertyColor), style()->colorSpace());
-        
+        paintInfo.context->setFillColor(style()->visitedDependentColor(CSSPropertyColor));
+
         // Draw the filename
         paintInfo.context->drawBidiText(font, textRunPaintInfo, IntPoint(roundToInt(textX), roundToInt(textY)));
-        
+
         if (input->icon()) {
             // Determine where the icon should be placed
             LayoutUnit iconY = paintOffset.y() + borderTop() + paddingTop() + (contentHeight() - iconHeight) / 2;
@@ -230,12 +230,12 @@
 
 HTMLInputElement* RenderFileUploadControl::uploadButton() const
 {
-    HTMLInputElement* input = static_cast<HTMLInputElement*>(node());
+    HTMLInputElement* input = toHTMLInputElement(node());
 
     ASSERT(input->shadow());
 
     Node* buttonNode = input->shadow()->oldestShadowRoot()->firstChild();
-    return buttonNode && buttonNode->isHTMLElement() && buttonNode->hasTagName(inputTag) ? static_cast<HTMLInputElement*>(buttonNode) : 0;
+    return buttonNode && buttonNode->isHTMLElement() && buttonNode->hasTagName(inputTag) ? toHTMLInputElement(buttonNode) : 0;
 }
 
 String RenderFileUploadControl::buttonValue()
@@ -248,7 +248,7 @@
 
 String RenderFileUploadControl::fileTextValue() const
 {
-    HTMLInputElement* input = static_cast<HTMLInputElement*>(node());
+    HTMLInputElement* input = toHTMLInputElement(node());
     ASSERT(input->files());
     return theme()->fileListNameForWidth(input->files(), style()->font(), maxFilenameWidth(), input->multiple());
 }
diff --git a/Source/core/rendering/RenderFlexibleBox.cpp b/Source/core/rendering/RenderFlexibleBox.cpp
index 0d5f8c2..c3085d0 100644
--- a/Source/core/rendering/RenderFlexibleBox.cpp
+++ b/Source/core/rendering/RenderFlexibleBox.cpp
@@ -863,9 +863,9 @@
     ASSERT(availableAlignmentSpace >= 0);
 
     bool isHorizontal = isHorizontalFlow();
-    Length start = isHorizontal ? child->style()->marginTop() : child->style()->marginLeft();
-    Length end = isHorizontal ? child->style()->marginBottom() : child->style()->marginRight();
-    if (start.isAuto() && end.isAuto()) {
+    Length topOrLeft = isHorizontal ? child->style()->marginTop() : child->style()->marginLeft();
+    Length bottomOrRight = isHorizontal ? child->style()->marginBottom() : child->style()->marginRight();
+    if (topOrLeft.isAuto() && bottomOrRight.isAuto()) {
         adjustAlignmentForChild(child, availableAlignmentSpace / 2);
         if (isHorizontal) {
             child->setMarginTop(availableAlignmentSpace / 2);
@@ -876,15 +876,32 @@
         }
         return true;
     }
-    if (start.isAuto()) {
-        adjustAlignmentForChild(child, availableAlignmentSpace);
+    bool shouldAdjustTopOrLeft = true;
+    if (isColumnFlow() && !child->style()->isLeftToRightDirection()) {
+        // For column flows, only make this adjustment if topOrLeft corresponds to the "before" margin,
+        // so that flipForRightToLeftColumn will do the right thing.
+        shouldAdjustTopOrLeft = false;
+    }
+    if (!isColumnFlow() && child->style()->isFlippedBlocksWritingMode()) {
+        // If we are a flipped writing mode, we need to adjust the opposite side. This is only needed
+        // for row flows because this only affects the block-direction axis.
+        shouldAdjustTopOrLeft = false;
+    }
+
+    if (topOrLeft.isAuto()) {
+        if (shouldAdjustTopOrLeft)
+            adjustAlignmentForChild(child, availableAlignmentSpace);
+
         if (isHorizontal)
             child->setMarginTop(availableAlignmentSpace);
         else
             child->setMarginLeft(availableAlignmentSpace);
         return true;
     }
-    if (end.isAuto()) {
+    if (bottomOrRight.isAuto()) {
+        if (!shouldAdjustTopOrLeft)
+            adjustAlignmentForChild(child, availableAlignmentSpace);
+
         if (isHorizontal)
             child->setMarginBottom(availableAlignmentSpace);
         else
@@ -1198,6 +1215,8 @@
         mainAxisOffset += flowAwareMarginStartForChild(child);
 
         LayoutUnit childMainExtent = mainAxisExtentForChild(child);
+        // In an RTL column situation, this will apply the margin-right/margin-end on the left.
+        // This will be fixed later in flipForRightToLeftColumn.
         LayoutPoint childLocation(shouldFlipMainAxis ? totalMainExtent - mainAxisOffset - childMainExtent : mainAxisOffset,
             crossAxisOffset + flowAwareMarginBeforeForChild(child));
 
@@ -1434,6 +1453,8 @@
         if (child->isOutOfFlowPositioned())
             continue;
         LayoutPoint location = flowAwareLocationForChild(child);
+        // For vertical flows, setFlowAwareLocationForChild will transpose x and y,
+        // so using the y axis for a column cross axis extent is correct.
         location.setY(crossExtent - crossAxisExtentForChild(child) - location.y());
         setFlowAwareLocationForChild(child, location);
     }
diff --git a/Source/core/rendering/RenderFlowThread.cpp b/Source/core/rendering/RenderFlowThread.cpp
index bff81ff..97c2ef6 100644
--- a/Source/core/rendering/RenderFlowThread.cpp
+++ b/Source/core/rendering/RenderFlowThread.cpp
@@ -261,7 +261,7 @@
     return regionClippingRect;
 }
 
-void RenderFlowThread::paintFlowThreadPortionInRegion(PaintInfo& paintInfo, RenderRegion* region, LayoutRect flowThreadPortionRect, LayoutRect flowThreadPortionOverflowRect, const LayoutPoint& paintOffset) const
+void RenderFlowThread::paintFlowThreadPortionInRegion(PaintInfo& paintInfo, RenderRegion* region, const LayoutRect& flowThreadPortionRect, const LayoutRect& flowThreadPortionOverflowRect, const LayoutPoint& paintOffset) const
 {
     GraphicsContext* context = paintInfo.context;
     if (!context)
@@ -314,7 +314,7 @@
     return RenderBlock::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction);
 }
 
-bool RenderFlowThread::hitTestFlowThreadPortionInRegion(RenderRegion* region, LayoutRect flowThreadPortionRect, LayoutRect flowThreadPortionOverflowRect, const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) const
+bool RenderFlowThread::hitTestFlowThreadPortionInRegion(RenderRegion* region, const LayoutRect& flowThreadPortionRect, const LayoutRect& flowThreadPortionOverflowRect, const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) const
 {
     LayoutRect regionClippingRect = computeRegionClippingRect(accumulatedOffset, flowThreadPortionRect, flowThreadPortionOverflowRect);
     if (!regionClippingRect.contains(locationInContainer.point()))
@@ -972,7 +972,7 @@
         overrideLogicalContentHeightComputed = true;
 
         // Compute the region height pretending that the offsetBreakInCurrentRegion is the logicalHeight for the auto-height region.
-        LayoutUnit regionOverrideLogicalContentHeight = region->computeReplacedLogicalHeightRespectingMinMaxHeight(offsetBreakInCurrentRegion);
+        LayoutUnit regionOverrideLogicalContentHeight = region->constrainContentBoxLogicalHeightByMinMax(offsetBreakInCurrentRegion, -1);
 
         // The new height of this region needs to be smaller than the initial value, the max height. A forced break is the only way to change the initial
         // height of an auto-height region besides content ending.
diff --git a/Source/core/rendering/RenderFlowThread.h b/Source/core/rendering/RenderFlowThread.h
index edaab40..c7bca53 100644
--- a/Source/core/rendering/RenderFlowThread.h
+++ b/Source/core/rendering/RenderFlowThread.h
@@ -80,8 +80,8 @@
     virtual void updateLogicalWidth() OVERRIDE FINAL;
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
 
-    void paintFlowThreadPortionInRegion(PaintInfo&, RenderRegion*, LayoutRect flowThreadPortionRect, LayoutRect flowThreadPortionOverflowRect, const LayoutPoint&) const;
-    bool hitTestFlowThreadPortionInRegion(RenderRegion*, LayoutRect flowThreadPortionRect, LayoutRect flowThreadPortionOverflowRect, const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) const;
+    void paintFlowThreadPortionInRegion(PaintInfo&, RenderRegion*, const LayoutRect& flowThreadPortionRect, const LayoutRect& flowThreadPortionOverflowRect, const LayoutPoint&) const;
+    bool hitTestFlowThreadPortionInRegion(RenderRegion*, const LayoutRect& flowThreadPortionRect, const LayoutRect& flowThreadPortionOverflowRect, const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) const;
 
     bool hasRegions() const { return m_regionList.size(); }
     // Check if the content is flown into at least a region with region styling rules.
diff --git a/Source/core/rendering/RenderFrameSet.cpp b/Source/core/rendering/RenderFrameSet.cpp
index 3aa2980..150922a 100644
--- a/Source/core/rendering/RenderFrameSet.cpp
+++ b/Source/core/rendering/RenderFrameSet.cpp
@@ -80,19 +80,18 @@
 {
     if (!paintInfo.rect.intersects(borderRect))
         return;
-        
+
     // FIXME: We should do something clever when borders from distinct framesets meet at a join.
-    
+
     // Fill first.
     GraphicsContext* context = paintInfo.context;
-    ColorSpace colorSpace = style()->colorSpace();
-    context->fillRect(borderRect, frameSet()->hasBorderColor() ? style()->visitedDependentColor(CSSPropertyBorderLeftColor) : borderFillColor(), colorSpace);
-    
+    context->fillRect(borderRect, frameSet()->hasBorderColor() ? style()->visitedDependentColor(CSSPropertyBorderLeftColor) : borderFillColor());
+
     // Now stroke the edges but only if we have enough room to paint both edges with a little
     // bit of the fill color showing through.
     if (borderRect.width() >= 3) {
-        context->fillRect(IntRect(borderRect.location(), IntSize(1, height())), borderStartEdgeColor(), colorSpace);
-        context->fillRect(IntRect(IntPoint(borderRect.maxX() - 1, borderRect.y()), IntSize(1, height())), borderEndEdgeColor(), colorSpace);
+        context->fillRect(IntRect(borderRect.location(), IntSize(1, height())), borderStartEdgeColor());
+        context->fillRect(IntRect(IntPoint(borderRect.maxX() - 1, borderRect.y()), IntSize(1, height())), borderEndEdgeColor());
     }
 }
 
@@ -102,22 +101,23 @@
         return;
 
     // FIXME: We should do something clever when borders from distinct framesets meet at a join.
-    
+
     // Fill first.
     GraphicsContext* context = paintInfo.context;
-    ColorSpace colorSpace = style()->colorSpace();
-    context->fillRect(borderRect, frameSet()->hasBorderColor() ? style()->visitedDependentColor(CSSPropertyBorderLeftColor) : borderFillColor(), colorSpace);
+    context->fillRect(borderRect, frameSet()->hasBorderColor() ? style()->visitedDependentColor(CSSPropertyBorderLeftColor) : borderFillColor());
 
     // Now stroke the edges but only if we have enough room to paint both edges with a little
     // bit of the fill color showing through.
     if (borderRect.height() >= 3) {
-        context->fillRect(IntRect(borderRect.location(), IntSize(width(), 1)), borderStartEdgeColor(), colorSpace);
-        context->fillRect(IntRect(IntPoint(borderRect.x(), borderRect.maxY() - 1), IntSize(width(), 1)), borderEndEdgeColor(), colorSpace);
+        context->fillRect(IntRect(borderRect.location(), IntSize(width(), 1)), borderStartEdgeColor());
+        context->fillRect(IntRect(IntPoint(borderRect.x(), borderRect.maxY() - 1), IntSize(width(), 1)), borderEndEdgeColor());
     }
 }
 
 void RenderFrameSet::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     if (paintInfo.phase != PaintPhaseForeground)
         return;
     
diff --git a/Source/core/rendering/RenderImage.cpp b/Source/core/rendering/RenderImage.cpp
index 9b30599..2094ed7 100644
--- a/Source/core/rendering/RenderImage.cpp
+++ b/Source/core/rendering/RenderImage.cpp
@@ -299,8 +299,8 @@
 
             // Draw an outline rect where the image should be.
             context->setStrokeStyle(SolidStroke);
-            context->setStrokeColor(Color::lightGray, style()->colorSpace());
-            context->setFillColor(Color::transparent, style()->colorSpace());
+            context->setStrokeColor(Color::lightGray);
+            context->setFillColor(Color::transparent);
             context->drawRect(pixelSnappedIntRect(LayoutRect(paintOffset.x() + leftBorder + leftPad, paintOffset.y() + topBorder + topPad, cWidth, cHeight)));
 
             bool errorPictureDrawn = false;
@@ -327,7 +327,7 @@
                 if (centerY < 0)
                     centerY = 0;
                 imageOffset = LayoutSize(leftBorder + leftPad + centerX + borderWidth, topBorder + topPad + centerY + borderWidth);
-                context->drawImage(image.get(), style()->colorSpace(), pixelSnappedIntRect(LayoutRect(paintOffset + imageOffset, imageSize)), CompositeSourceOver, shouldRespectImageOrientation());
+                context->drawImage(image.get(), pixelSnappedIntRect(LayoutRect(paintOffset + imageOffset, imageSize)), CompositeSourceOver, shouldRespectImageOrientation());
                 errorPictureDrawn = true;
             }
 
@@ -346,7 +346,7 @@
                 LayoutUnit textWidth = font.width(textRun);
                 TextRunPaintInfo textRunPaintInfo(textRun);
                 textRunPaintInfo.bounds = FloatRect(textRectOrigin, FloatSize(textWidth, fontMetrics.height()));
-                context->setFillColor(style()->visitedDependentColor(CSSPropertyColor), style()->colorSpace());
+                context->setFillColor(style()->visitedDependentColor(CSSPropertyColor));
                 if (errorPictureDrawn) {
                     if (usableWidth >= textWidth && fontMetrics.height() <= imageOffset.height())
                         context->drawText(font, textRunPaintInfo, textOrigin);
@@ -447,7 +447,7 @@
     CompositeOperator compositeOperator = imageElt ? imageElt->compositeOperator() : CompositeSourceOver;
     Image* image = m_imageResource->image().get();
     bool useLowQualityScaling = shouldPaintAtLowQuality(context, image, image, alignedRect.size());
-    context->drawImage(m_imageResource->image(alignedRect.width(), alignedRect.height()).get(), style()->colorSpace(), alignedRect, compositeOperator, shouldRespectImageOrientation(), useLowQualityScaling);
+    context->drawImage(m_imageResource->image(alignedRect.width(), alignedRect.height()).get(), alignedRect, compositeOperator, shouldRespectImageOrientation(), useLowQualityScaling);
 }
 
 bool RenderImage::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox*) const
@@ -526,7 +526,7 @@
         return;
 
     if (node()->hasTagName(inputTag))
-        m_altText = static_cast<HTMLInputElement*>(node())->altText();
+        m_altText = toHTMLInputElement(node())->altText();
     else if (node()->hasTagName(imgTag))
         m_altText = static_cast<HTMLImageElement*>(node())->altText();
 }
diff --git a/Source/core/rendering/RenderInline.cpp b/Source/core/rendering/RenderInline.cpp
index e0eb881..31c4b05 100644
--- a/Source/core/rendering/RenderInline.cpp
+++ b/Source/core/rendering/RenderInline.cpp
@@ -526,6 +526,7 @@
 
 void RenderInline::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
     m_lineBoxes.paint(this, paintInfo, paintOffset);
 }
 
diff --git a/Source/core/rendering/RenderInputSpeech.cpp b/Source/core/rendering/RenderInputSpeech.cpp
index 5c0c7b7..c6e83ee 100644
--- a/Source/core/rendering/RenderInputSpeech.cpp
+++ b/Source/core/rendering/RenderInputSpeech.cpp
@@ -44,7 +44,7 @@
 static const float minSpeechButtonSize = 8;
 static const float maxSpeechButtonSize = 40;
 
-void RenderInputSpeech::adjustInputFieldSpeechButtonStyle(StyleResolver*, RenderStyle* style, Element*)
+void RenderInputSpeech::adjustInputFieldSpeechButtonStyle(RenderStyle* style, Element*)
 {
     // Scale the button size based on the font size.
     float fontScale = style->fontSize() / defaultControlFontPixelSize;
@@ -92,7 +92,7 @@
         image = imageStateRecording.get();
     else if (speechButton->state() == InputFieldSpeechButtonElement::Recognizing)
         image = imageStateWaiting.get();
-    paintInfo.context->drawImage(image, object->style()->colorSpace(), pixelSnappedIntRect(buttonRect));
+    paintInfo.context->drawImage(image, pixelSnappedIntRect(buttonRect));
 
     return false;
 }
diff --git a/Source/core/rendering/RenderInputSpeech.h b/Source/core/rendering/RenderInputSpeech.h
index 6735961..e1d8c6e 100644
--- a/Source/core/rendering/RenderInputSpeech.h
+++ b/Source/core/rendering/RenderInputSpeech.h
@@ -45,7 +45,7 @@
 
 class RenderInputSpeech {
 public:
-    static void adjustInputFieldSpeechButtonStyle(StyleResolver*, RenderStyle*, Element*);
+    static void adjustInputFieldSpeechButtonStyle(RenderStyle*, Element*);
     static bool paintInputFieldSpeechButton(RenderObject*, const PaintInfo&, const IntRect&);
 };
 
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index 6fd7c24..2697684 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -46,8 +46,9 @@
 
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
-#include "core/css/resolver/StyleResolver.h"
+#include "core/css/PseudoStyleRequest.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentEventQueue.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
@@ -55,6 +56,7 @@
 #include "core/editing/FrameSelection.h"
 #include "core/html/HTMLFrameElement.h"
 #include "core/html/HTMLFrameOwnerElement.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FocusController.h"
 #include "core/page/Frame.h"
@@ -70,6 +72,7 @@
 #include "core/platform/ScrollAnimator.h"
 #include "core/platform/Scrollbar.h"
 #include "core/platform/ScrollbarTheme.h"
+#include "core/platform/chromium/TraceEvent.h"
 #include "core/platform/graphics/FloatPoint3D.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
@@ -129,9 +132,10 @@
     , m_hasSelfPaintingLayerDescendantDirty(false)
     , m_hasOutOfFlowPositionedDescendant(false)
     , m_hasOutOfFlowPositionedDescendantDirty(true)
+    , m_hasUnclippedDescendant(false)
     , m_needsCompositedScrolling(false)
-    , m_descendantsAreContiguousInStackingOrder(false)
-    , m_descendantsAreContiguousInStackingOrderDirty(true)
+    , m_canBePromotedToStackingContainer(false)
+    , m_canBePromotedToStackingContainerDirty(true)
     , m_isRootLayer(renderer->isRenderView())
     , m_usedTransparency(false)
     , m_paintingInsideReflection(false)
@@ -164,6 +168,7 @@
     , m_scrollCorner(0)
     , m_resizer(0)
     , m_enclosingPaginationLayer(0)
+    , m_forceNeedsCompositedScrolling(DoNotForceCompositedScrolling)
 {
     m_isNormalFlowOnly = shouldBeNormalFlowOnly();
     m_isSelfPaintingLayer = shouldBeSelfPaintingLayer();
@@ -212,6 +217,9 @@
             toElement(node)->setSavedLayerScrollOffset(m_scrollOffset);
     }
 
+    if (!m_renderer->documentBeingDestroyed())
+        compositor()->removeOutOfFlowPositionedLayer(this);
+
     destroyScrollbar(HorizontalScrollbar);
     destroyScrollbar(VerticalScrollbar);
 
@@ -462,166 +470,100 @@
     }
 }
 
+void RenderLayer::setAncestorChainHasOutOfFlowPositionedDescendant()
+{
+    for (RenderLayer* layer = this; layer; layer = layer->parent()) {
+        if (!layer->m_hasOutOfFlowPositionedDescendantDirty && layer->hasOutOfFlowPositionedDescendant())
+            break;
+
+        layer->setHasOutOfFlowPositionedDescendantDirty(false);
+        layer->setHasOutOfFlowPositionedDescendant(true);
+    }
+}
+
+void RenderLayer::dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus()
+{
+    for (RenderLayer* layer = this; layer; layer = layer->parent()) {
+        layer->setHasOutOfFlowPositionedDescendantDirty(true);
+
+        // We may or may not have an unclipped descendant. If we do, we'll reset
+        // this to true the next time composited scrolling state is updated.
+        layer->setHasUnclippedDescendant(false);
+
+        // If we have reached an out of flow positioned layer, we know our parent should have an out-of-flow positioned descendant.
+        // In this case, there is no need to dirty our ancestors further.
+        if (layer->renderer()->isOutOfFlowPositioned()) {
+            ASSERT(!parent() || parent()->m_hasOutOfFlowPositionedDescendantDirty || parent()->hasOutOfFlowPositionedDescendant());
+            break;
+        }
+    }
+}
+
 bool RenderLayer::acceleratedCompositingForOverflowScrollEnabled() const
 {
-    return renderer()->frame()
-        && renderer()->frame()->page()
-        && renderer()->frame()->page()->settings()->acceleratedCompositingForOverflowScrollEnabled();
+    const Settings* settings = renderer()->document()->settings();
+    return settings && settings->acceleratedCompositingForOverflowScrollEnabled();
 }
 
-// If we are a stacking container, then this function will determine if our
-// descendants for a contiguous block in stacking order. This is required in
-// order for an element to be safely promoted to a stacking container. It is safe
-// to become a stacking container if this change would not alter the stacking
-// order of layers on the page. That can only happen if a non-descendant appear
-// between us and our descendants in stacking order. Here's an example:
-//
-//                                 this
-//                                /  |  \.
-//                               A   B   C
-//                              /\   |   /\.
-//                             0 -8  D  2  7
-//                                   |
-//                                   5
-//
-// I've labeled our normal flow descendants A, B, C, and D, our stacking
-// container descendants with their z indices, and us with 'this' (we're a
-// stacking container and our zIndex doesn't matter here). These nodes appear in
-// three lists: posZOrder, negZOrder, and normal flow (keep in mind that normal
-// flow layers don't overlap). So if we arrange these lists in order we get our
-// stacking order:
-//
-//                     [-8], [A-D], [0, 2, 5, 7]--> pos z-order.
-//                       |     |
-//        Neg z-order. <-+     +--> Normal flow descendants.
-//
-// We can then assign new, 'stacking' order indices to these elements as follows:
-//
-//                     [-8], [A-D], [0, 2, 5, 7]
-// 'Stacking' indices:  -1     0     1  2  3  4
-//
-// Note that the normal flow descendants can share an index because they don't
-// stack/overlap. Now our problem becomes very simple: a layer can safely become
-// a stacking container if the stacking-order indices of it and its descendants
-// appear in a contiguous block in the list of stacking indices. This problem
-// can be solved very efficiently by calculating the min/max stacking indices in
-// the subtree, and the number stacking container descendants. Once we have this
-// information, we know that the subtree's indices form a contiguous block if:
-//
-//           maxStackIndex - minStackIndex == numSCDescendants
-//
-// So for node A in the example above we would have:
-//   maxStackIndex = 1
-//   minStackIndex = -1
-//   numSCDecendants = 2
-//
-// and so,
-//       maxStackIndex - minStackIndex == numSCDescendants
-//  ===>                      1 - (-1) == 2
-//  ===>                             2 == 2
-//
-//  Since this is true, A can safely become a stacking container.
-//  Now, for node C we have:
-//
-//   maxStackIndex = 4
-//   minStackIndex = 0 <-- because C has stacking index 0.
-//   numSCDecendants = 2
-//
-// and so,
-//       maxStackIndex - minStackIndex == numSCDescendants
-//  ===>                         4 - 0 == 2
-//  ===>                             4 == 2
-//
-// Since this is false, C cannot be safely promoted to a stacking container. This
-// happened because of the elements with z-index 5 and 0. Now if 5 had been a
-// child of C rather than D, and A had no child with Z index 0, we would have had:
-//
-//   maxStackIndex = 3
-//   minStackIndex = 0 <-- because C has stacking index 0.
-//   numSCDecendants = 3
-//
-// and so,
-//       maxStackIndex - minStackIndex == numSCDescendants
-//  ===>                         3 - 0 == 3
-//  ===>                             3 == 3
-//
-//  And we would conclude that C could be promoted.
-void RenderLayer::updateDescendantsAreContiguousInStackingOrder()
+// Determine whether the current layer can be promoted to a stacking container.
+// We do this by computing what positive and negative z-order lists would look
+// like before and after promotion, and ensuring that proper stacking order is
+// preserved between the two sets of lists.
+void RenderLayer::updateCanBeStackingContainer()
 {
-    if (!m_descendantsAreContiguousInStackingOrderDirty || !isStackingContext() || !acceleratedCompositingForOverflowScrollEnabled())
+    TRACE_EVENT0("blink_rendering", "RenderLayer::updateCanBeStackingContainer");
+
+    if (isStackingContext() || !m_canBePromotedToStackingContainerDirty || !acceleratedCompositingForOverflowScrollEnabled())
         return;
 
-    ASSERT(!m_normalFlowListDirty);
-    ASSERT(!m_zOrderListsDirty);
-
-    OwnPtr<Vector<RenderLayer*> > posZOrderList;
-    OwnPtr<Vector<RenderLayer*> > negZOrderList;
-    rebuildZOrderLists(StopAtStackingContexts, posZOrderList, negZOrderList);
-
-    // Create a reverse lookup.
-    HashMap<const RenderLayer*, int> lookup;
-
-    if (negZOrderList) {
-        int stackingOrderIndex = -1;
-        size_t listSize = negZOrderList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* currentLayer = negZOrderList->at(listSize - i - 1);
-            if (!currentLayer->isStackingContext())
-                continue;
-            lookup.set(currentLayer, stackingOrderIndex--);
-        }
-    }
-
-    if (posZOrderList) {
-        size_t listSize = posZOrderList->size();
-        int stackingOrderIndex = 1;
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* currentLayer = posZOrderList->at(i);
-            if (!currentLayer->isStackingContext())
-                continue;
-            lookup.set(currentLayer, stackingOrderIndex++);
-        }
-    }
-
-    int minIndex = 0;
-    int maxIndex = 0;
-    int count = 0;
-    bool firstIteration = true;
-    updateDescendantsAreContiguousInStackingOrderRecursive(lookup, minIndex, maxIndex, count, firstIteration);
-
-    m_descendantsAreContiguousInStackingOrderDirty = false;
-}
-
-void RenderLayer::updateDescendantsAreContiguousInStackingOrderRecursive(const HashMap<const RenderLayer*, int>& lookup, int& minIndex, int& maxIndex, int& count, bool firstIteration)
-{
-    if (isStackingContext() && !firstIteration) {
-        if (lookup.contains(this)) {
-            minIndex = std::min(minIndex, lookup.get(this));
-            maxIndex = std::max(maxIndex, lookup.get(this));
-            count++;
-        }
+    FrameView* frameView = renderer()->view()->frameView();
+    if (!frameView || !frameView->containsScrollableArea(this))
         return;
+
+    RenderLayer* ancestorStackingContext = this->ancestorStackingContext();
+    if (!ancestorStackingContext)
+        return;
+
+    OwnPtr<Vector<RenderLayer*> > posZOrderListBeforePromote = adoptPtr(new Vector<RenderLayer*>);
+    OwnPtr<Vector<RenderLayer*> > negZOrderListBeforePromote = adoptPtr(new Vector<RenderLayer*>);
+    OwnPtr<Vector<RenderLayer*> > posZOrderListAfterPromote = adoptPtr(new Vector<RenderLayer*>);
+    OwnPtr<Vector<RenderLayer*> > negZOrderListAfterPromote = adoptPtr(new Vector<RenderLayer*>);
+
+    collectBeforePromotionZOrderList(ancestorStackingContext, posZOrderListBeforePromote, negZOrderListBeforePromote);
+    collectAfterPromotionZOrderList(ancestorStackingContext, posZOrderListAfterPromote, negZOrderListAfterPromote);
+
+    size_t maxIndex = std::min(posZOrderListAfterPromote->size() + negZOrderListAfterPromote->size(), posZOrderListBeforePromote->size() + negZOrderListBeforePromote->size());
+
+    m_canBePromotedToStackingContainerDirty = false;
+    m_canBePromotedToStackingContainer = false;
+
+    const RenderLayer* layerAfterPromote = 0;
+    for (size_t i = 0; i < maxIndex && layerAfterPromote != this; ++i) {
+        const RenderLayer* layerBeforePromote = i < negZOrderListBeforePromote->size()
+            ? negZOrderListBeforePromote->at(i)
+            : posZOrderListBeforePromote->at(i - negZOrderListBeforePromote->size());
+        layerAfterPromote = i < negZOrderListAfterPromote->size()
+            ? negZOrderListAfterPromote->at(i)
+            : posZOrderListAfterPromote->at(i - negZOrderListAfterPromote->size());
+
+        if (layerBeforePromote != layerAfterPromote && (layerAfterPromote != this || renderer()->hasBackground()))
+            return;
     }
 
-    for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
-        int childMinIndex = 0;
-        int childMaxIndex = 0;
-        int childCount = 0;
-        child->updateDescendantsAreContiguousInStackingOrderRecursive(lookup, childMinIndex, childMaxIndex, childCount, false);
-        if (childCount) {
-            count += childCount;
-            minIndex = std::min(minIndex, childMinIndex);
-            maxIndex = std::max(maxIndex, childMaxIndex);
-        }
+    layerAfterPromote = 0;
+    for (size_t i = 0; i < maxIndex && layerAfterPromote != this; ++i) {
+        const RenderLayer* layerBeforePromote = i < posZOrderListBeforePromote->size()
+            ? posZOrderListBeforePromote->at(posZOrderListBeforePromote->size() - i - 1)
+            : negZOrderListBeforePromote->at(negZOrderListBeforePromote->size() + posZOrderListBeforePromote->size() - i - 1);
+        layerAfterPromote = i < posZOrderListAfterPromote->size()
+            ? posZOrderListAfterPromote->at(posZOrderListAfterPromote->size() - i - 1)
+            : negZOrderListAfterPromote->at(negZOrderListAfterPromote->size() + posZOrderListAfterPromote->size() - i - 1);
+
+        if (layerBeforePromote != layerAfterPromote && layerAfterPromote != this)
+            return;
     }
 
-    if (!isStackingContext()) {
-        bool newValue = maxIndex - minIndex == count;
-        bool didUpdate = newValue != m_descendantsAreContiguousInStackingOrder;
-        m_descendantsAreContiguousInStackingOrder = newValue;
-        if (didUpdate)
-            updateNeedsCompositedScrolling();
-    }
+    m_canBePromotedToStackingContainer = true;
 }
 
 static inline bool isPositionedContainer(const RenderLayer* layer)
@@ -635,17 +577,7 @@
 
 void RenderLayer::collectBeforePromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListBeforePromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListBeforePromote)
 {
-    // FIXME: TemporaryChange should support bit fields.
-    bool oldNeedsCompositedScrolling = m_needsCompositedScrolling;
-    bool oldIsNormalFlowOnly = m_isNormalFlowOnly;
-
-    m_needsCompositedScrolling = false;
-    m_isNormalFlowOnly = shouldBeNormalFlowOnly();
-
-    ancestorStackingContext->rebuildZOrderLists(StopAtStackingContexts, posZOrderListBeforePromote, negZOrderListBeforePromote, 0);
-
-    m_needsCompositedScrolling = oldNeedsCompositedScrolling;
-    m_isNormalFlowOnly = oldIsNormalFlowOnly;
+    ancestorStackingContext->rebuildZOrderLists(posZOrderListBeforePromote, negZOrderListBeforePromote, this, OnlyStackingContextsCanBeStackingContainers);
 
     const RenderLayer* positionedAncestor = parent();
     while (positionedAncestor && !isPositionedContainer(positionedAncestor) && !positionedAncestor->isStackingContext())
@@ -676,17 +608,7 @@
 
 void RenderLayer::collectAfterPromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListAfterPromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListAfterPromote)
 {
-    // FIXME: TemporaryChange should support bit fields.
-    bool oldNeedsCompositedScrolling = m_needsCompositedScrolling;
-    bool oldIsNormalFlowOnly = m_isNormalFlowOnly;
-
-    m_isNormalFlowOnly = false;
-    m_needsCompositedScrolling = true;
-
-    ancestorStackingContext->rebuildZOrderLists(StopAtStackingContexts, posZOrderListAfterPromote, negZOrderListAfterPromote, this);
-
-    m_needsCompositedScrolling = oldNeedsCompositedScrolling;
-    m_isNormalFlowOnly = oldIsNormalFlowOnly;
+    ancestorStackingContext->rebuildZOrderLists(posZOrderListAfterPromote, negZOrderListAfterPromote, this, ForceLayerToStackingContainer);
 }
 
 // Compute what positive and negative z-order lists would look like before and
@@ -1055,7 +977,8 @@
     if (isStackingContext() || !ancestorStackingContainer())
         return true;
 
-    return m_descendantsAreContiguousInStackingOrder;
+    ASSERT(!m_canBePromotedToStackingContainerDirty);
+    return m_canBePromotedToStackingContainer;
 }
 
 void RenderLayer::setHasVisibleContent()
@@ -1111,56 +1034,51 @@
     }
 }
 
-void RenderLayer::updateDescendantDependentFlags(HashSet<const RenderObject*>* outOfFlowDescendantContainingBlocks)
+void RenderLayer::updateHasUnclippedDescendant()
+{
+    TRACE_EVENT0("blink_rendering", "RenderLayer::updateHasUnclippedDescendant");
+    ASSERT(renderer()->isOutOfFlowPositioned());
+    if (!m_hasVisibleContent && !m_hasVisibleDescendant)
+        return;
+
+    const RenderObject* containingBlock = renderer()->containingBlock();
+    for (RenderLayer* ancestor = parent(); ancestor && ancestor->renderer() != containingBlock; ancestor = ancestor->parent())
+        ancestor->setHasUnclippedDescendant(true);
+}
+
+static bool subtreeContainsOutOfFlowPositionedLayer(const RenderLayer* subtreeRoot)
+{
+    return (subtreeRoot->renderer() && subtreeRoot->renderer()->isOutOfFlowPositioned()) || subtreeRoot->hasOutOfFlowPositionedDescendant();
+}
+
+void RenderLayer::updateDescendantDependentFlags()
 {
     if (m_visibleDescendantStatusDirty || m_hasSelfPaintingLayerDescendantDirty || m_hasOutOfFlowPositionedDescendantDirty) {
-        const bool hadVisibleDescendant = m_hasVisibleDescendant;
-        const bool hadOutOfFlowPositionedDescendant = m_hasOutOfFlowPositionedDescendant;
-
         m_hasVisibleDescendant = false;
         m_hasSelfPaintingLayerDescendant = false;
         m_hasOutOfFlowPositionedDescendant = false;
 
-        HashSet<const RenderObject*> childOutOfFlowDescendantContainingBlocks;
         for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
-            childOutOfFlowDescendantContainingBlocks.clear();
-            child->updateDescendantDependentFlags(&childOutOfFlowDescendantContainingBlocks);
-
-            bool childIsOutOfFlowPositioned = child->renderer() && child->renderer()->isOutOfFlowPositioned();
-            if (childIsOutOfFlowPositioned)
-                childOutOfFlowDescendantContainingBlocks.add(child->renderer()->containingBlock());
-
-            if (outOfFlowDescendantContainingBlocks) {
-                HashSet<const RenderObject*>::const_iterator it = childOutOfFlowDescendantContainingBlocks.begin();
-                for (; it != childOutOfFlowDescendantContainingBlocks.end(); ++it)
-                    outOfFlowDescendantContainingBlocks->add(*it);
-            }
+            child->updateDescendantDependentFlags();
 
             bool hasVisibleDescendant = child->m_hasVisibleContent || child->m_hasVisibleDescendant;
             bool hasSelfPaintingLayerDescendant = child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant();
-            bool hasOutOfFlowPositionedDescendant = hasVisibleDescendant && (!childOutOfFlowDescendantContainingBlocks.isEmpty() || child->hasOutOfFlowPositionedDescendant());
+            bool hasOutOfFlowPositionedDescendant = subtreeContainsOutOfFlowPositionedLayer(child);
 
             m_hasVisibleDescendant |= hasVisibleDescendant;
             m_hasSelfPaintingLayerDescendant |= hasSelfPaintingLayerDescendant;
             m_hasOutOfFlowPositionedDescendant |= hasOutOfFlowPositionedDescendant;
 
-            if (m_hasVisibleDescendant && m_hasSelfPaintingLayerDescendant && m_hasOutOfFlowPositionedDescendant)
+            if (m_hasVisibleDescendant && m_hasSelfPaintingLayerDescendant && hasOutOfFlowPositionedDescendant)
                 break;
         }
 
-        if (outOfFlowDescendantContainingBlocks && renderer())
-            outOfFlowDescendantContainingBlocks->remove(renderer());
-
         m_visibleDescendantStatusDirty = false;
         m_hasSelfPaintingLayerDescendantDirty = false;
         m_hasOutOfFlowPositionedDescendantDirty = false;
-
-        if (m_hasVisibleDescendant != hadVisibleDescendant || m_hasOutOfFlowPositionedDescendant != hadOutOfFlowPositionedDescendant)
-            updateNeedsCompositedScrolling();
     }
 
     if (m_visibleContentStatusDirty) {
-        const bool hadVisibleContent = m_hasVisibleContent;
         if (renderer()->style()->visibility() == VISIBLE)
             m_hasVisibleContent = true;
         else {
@@ -1186,10 +1104,8 @@
                         r = r->nextSibling();
                 }
             }
-        }    
-        m_visibleContentStatusDirty = false; 
-        if (hadVisibleContent != m_hasVisibleContent)
-            updateNeedsCompositedScrolling();
+        }
+        m_visibleContentStatusDirty = false;
     }
 }
 
@@ -1508,13 +1424,8 @@
     LayoutRect parentLayerRect = renderer()->localToContainerQuad(repaintQuad, parentLayer->renderer()).enclosingBoundingBox();
     
     if (parentLayer->isComposited()) {
-        if (!parentLayer->backing()->paintsIntoWindow()) {
-            parentLayer->setBackingNeedsRepaintInRect(parentLayerRect);
-            return;
-        }
-        // If the painting goes to window, redirect the painting to the parent RenderView.
-        parentLayer = renderer()->view()->layer();
-        parentLayerRect = renderer()->localToContainerQuad(repaintQuad, parentLayer->renderer()).enclosingBoundingBox();
+        parentLayer->setBackingNeedsRepaintInRect(parentLayerRect);
+        return;
     }
 
     if (parentLayer->paintsWithFilters()) {
@@ -1708,7 +1619,7 @@
         context->clip(clipRect);
         context->beginTransparencyLayer(renderer()->opacity());
 #ifdef REVEAL_TRANSPARENCY_LAYERS
-        context->setFillColor(Color(0.0f, 0.0f, 0.5f, 0.2f), ColorSpaceDeviceRGB);
+        context->setFillColor(Color(0.0f, 0.0f, 0.5f, 0.2f));
         context->fillRect(clipRect);
 #endif
     }
@@ -1760,16 +1671,6 @@
         // case where we're building up generated content layers. This is ok, since the lists will start
         // off dirty in that case anyway.
         child->dirtyStackingContainerZOrderLists();
-
-        // Adding an out of flow positioned descendant can only affect
-        // the opt-in decision for layers beneath and including our
-        // containing block.
-        RenderObject* containingBlock = child->renderer()->containingBlock();
-        for (RenderLayer* layer = child; layer; layer = layer->parent()) {
-            layer->updateNeedsCompositedScrolling();
-            if (layer->renderer() == containingBlock)
-                break;
-        }
     }
 
     child->updateDescendantDependentFlags();
@@ -1779,8 +1680,14 @@
     if (child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant())
         setAncestorChainHasSelfPaintingLayerDescendant();
 
-    if (child->renderer() && (child->renderer()->isOutOfFlowPositioned() || child->hasOutOfFlowPositionedDescendant()))
-        setAncestorChainHasOutOfFlowPositionedDescendant(child->renderer()->containingBlock());
+    if (subtreeContainsOutOfFlowPositionedLayer(child)) {
+        // Now that the out of flow positioned descendant is in the tree, we
+        // need to tell the compositor to reevaluate the compositing
+        // requirements since we may be able to mark more layers as having
+        // an 'unclipped' descendant.
+        compositor()->setNeedsUpdateCompositingRequirementsState();
+        setAncestorChainHasOutOfFlowPositionedDescendant();
+    }
 
     compositor()->layerWasAdded(this, child);
 }
@@ -1808,28 +1715,21 @@
         // reattachment process in removeOnlyThisLayer, the layer may already be disconnected
         // from the main layer tree, so we need to null-check the |stackingContainer| value.
         oldChild->dirtyStackingContainerZOrderLists();
-
-        // This could affect whether or not a layer has an out of flow
-        // positioned descendant so we need to schedule some updates.
-        // Removing an out of flow positioned descendant can only affect
-        // the opt-in decision for layers beneath and including the old child's
-        // containing block.
-        RenderObject* containingBlock = oldChild->renderer()->containingBlock();
-        for (RenderLayer* layer = this; layer; layer = layer->parent()) {
-            layer->updateNeedsCompositedScrolling();
-            if (layer->renderer() == containingBlock)
-                break;
-        }
     }
 
-    if ((oldChild->renderer() && oldChild->renderer()->isOutOfFlowPositioned()) || oldChild->hasOutOfFlowPositionedDescendant())
-        dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
-
     oldChild->setPreviousSibling(0);
     oldChild->setNextSibling(0);
     oldChild->setParent(0);
 
     oldChild->updateDescendantDependentFlags();
+    if (subtreeContainsOutOfFlowPositionedLayer(oldChild)) {
+        // It may now be the case that a layer no longer has an unclipped
+        // descendant. Let the compositor know that it needs to reevaluate
+        // its compositing requirements to check this.
+        compositor()->setNeedsUpdateCompositingRequirementsState();
+        dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
+    }
+
     if (oldChild->m_hasVisibleContent || oldChild->m_hasVisibleDescendant)
         dirtyAncestorChainVisibleDescendantStatus();
 
@@ -2044,39 +1944,71 @@
 
 bool RenderLayer::needsCompositedScrolling() const
 {
+    switch (m_forceNeedsCompositedScrolling) {
+    case DoNotForceCompositedScrolling:
+        return m_needsCompositedScrolling;
+    case CompositedScrollingAlwaysOn:
+        return true;
+    case CompositedScrollingAlwaysOff:
+        return false;
+    }
+
+    ASSERT_NOT_REACHED();
     return m_needsCompositedScrolling;
 }
 
 void RenderLayer::updateNeedsCompositedScrolling()
 {
+    updateCanBeStackingContainer();
+
     bool needsCompositedScrolling = false;
+    updateDescendantDependentFlags();
 
-    FrameView* frameView = renderer()->view()->frameView();
-    if (frameView && frameView->containsScrollableArea(this)) {
-        updateDescendantDependentFlags();
-
-        bool forceUseCompositedScrolling = acceleratedCompositingForOverflowScrollEnabled()
-            && canBeStackingContainer()
-            && !hasOutOfFlowPositionedDescendant();
+    ASSERT(renderer()->view()->frameView() && renderer()->view()->frameView()->containsScrollableArea(this));
+    bool forceUseCompositedScrolling = acceleratedCompositingForOverflowScrollEnabled()
+        && canBeStackingContainer()
+        && !hasUnclippedDescendant();
 
 #if ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
-        needsCompositedScrolling = forceUseCompositedScrolling || renderer()->style()->useTouchOverflowScrolling();
+    needsCompositedScrolling = forceUseCompositedScrolling || renderer()->style()->useTouchOverflowScrolling();
 #else
-        needsCompositedScrolling = forceUseCompositedScrolling;
+    needsCompositedScrolling = forceUseCompositedScrolling;
 #endif
-        // We gather a boolean value for use with Google UMA histograms to
-        // quantify the actual effects of a set of patches attempting to
-        // relax composited scrolling requirements, thereby increasing the
-        // number of composited overflow divs.
-        if (acceleratedCompositingForOverflowScrollEnabled())
-            HistogramSupport::histogramEnumeration("Renderer.NeedsCompositedScrolling", needsCompositedScrolling, 2);
-    }
+    // We gather a boolean value for use with Google UMA histograms to
+    // quantify the actual effects of a set of patches attempting to
+    // relax composited scrolling requirements, thereby increasing the
+    // number of composited overflow divs.
+    if (acceleratedCompositingForOverflowScrollEnabled())
+        HistogramSupport::histogramEnumeration("Renderer.NeedsCompositedScrolling", needsCompositedScrolling, 2);
 
+    setNeedsCompositedScrolling(needsCompositedScrolling);
+}
+
+void RenderLayer::setNeedsCompositedScrolling(bool needsCompositedScrolling)
+{
     if (m_needsCompositedScrolling == needsCompositedScrolling)
         return;
 
     m_needsCompositedScrolling = needsCompositedScrolling;
 
+    // Note, the z-order lists may need to be rebuilt, but our code guarantees
+    // that we have not affected stacking, so we will not dirty
+    // m_canBePromotedToStackingContainer for either us or our stacking context
+    // or container.
+    didUpdateNeedsCompositedScrolling();
+}
+
+void RenderLayer::setForceNeedsCompositedScrolling(RenderLayer::ForceNeedsCompositedScrollingMode mode)
+{
+    if (m_forceNeedsCompositedScrolling == mode)
+        return;
+
+    m_forceNeedsCompositedScrolling = mode;
+    didUpdateNeedsCompositedScrolling();
+}
+
+void RenderLayer::didUpdateNeedsCompositedScrolling()
+{
     updateIsNormalFlowOnly();
     updateSelfPaintingLayer();
 
@@ -2152,11 +2084,11 @@
         IntSize remainingScrollOffset = newScrollOffset - adjustedScrollOffset();
         if (!remainingScrollOffset.isZero() && renderer()->parent()) {
             if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
-                scrollableLayer->scrollByRecursively(remainingScrollOffset);
+                scrollableLayer->scrollByRecursively(remainingScrollOffset, clamp);
 
             Frame* frame = renderer()->frame();
-            if (frame)
-                frame->eventHandler()->updateAutoscrollRenderer();
+            if (frame && frame->page())
+                frame->page()->updateAutoscrollRenderer();
         }
     } else if (renderer()->view()->frameView()) {
         // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
@@ -2194,7 +2126,7 @@
     if (!box)
         return;
 
-    if (box->style()->overflowX() != OMARQUEE) {
+    if (!box->isHTMLMarquee()) {
         // Ensure that the dimensions will be computed if they need to be (for overflow:hidden blocks).
         if (m_scrollDimensionsDirty)
             computeScrollDimensions();
@@ -2275,7 +2207,10 @@
 
     // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
     // like navigation to an anchor.
-    return !frameView->frame()->eventHandler()->autoscrollInProgress();
+    Page* page = frameView->frame()->page();
+    if (!page)
+        return false;
+    return !page->autoscrollInProgress();
 }
 
 void RenderLayer::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
@@ -3216,7 +3151,7 @@
 
     computeScrollDimensions();
 
-    if (box->style()->overflowX() != OMARQUEE) {
+    if (!box->isHTMLMarquee()) {
         // Layout may cause us to be at an invalid scroll position. In this case we need
         // to pull our scroll offsets back to the max (or push them up to the min).
         IntSize clampedScrollOffset = clampScrollOffset(adjustedScrollOffset());
@@ -3339,7 +3274,7 @@
     // We don't want to paint white if we have overlay scrollbars, since we need
     // to see what is behind it.
     if (!hasOverlayScrollbars())
-        context->fillRect(absRect, Color::white, box->style()->colorSpace());
+        context->fillRect(absRect, Color::white);
 }
 
 void RenderLayer::drawPlatformResizerImage(GraphicsContext* context, IntRect resizerCornerRect)
@@ -3363,12 +3298,12 @@
         context->save();
         context->translate(resizerCornerRect.x() + cornerResizerSize.width(), resizerCornerRect.y() + resizerCornerRect.height() - cornerResizerSize.height());
         context->scale(FloatSize(-1.0, 1.0));
-        context->drawImage(resizeCornerImage.get(), renderer()->style()->colorSpace(), IntRect(IntPoint(), cornerResizerSize));
+        context->drawImage(resizeCornerImage.get(), IntRect(IntPoint(), cornerResizerSize));
         context->restore();
         return;
     }
     IntRect imageRect(resizerCornerRect.maxXMaxYCorner() - cornerResizerSize, cornerResizerSize);
-    context->drawImage(resizeCornerImage.get(), renderer()->style()->colorSpace(), imageRect);
+    context->drawImage(resizeCornerImage.get(), imageRect);
 }
 
 void RenderLayer::paintResizer(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
@@ -3388,7 +3323,7 @@
         updateResizerStyle();
         return;
     }
-    
+
     if (m_resizer) {
         m_resizer->paintIntoRect(context, paintOffset, absRect);
         return;
@@ -3403,9 +3338,9 @@
         context->clip(absRect);
         IntRect largerCorner = absRect;
         largerCorner.setSize(IntSize(largerCorner.width() + 1, largerCorner.height() + 1));
-        context->setStrokeColor(Color(makeRGB(217, 217, 217)), ColorSpaceDeviceRGB);
+        context->setStrokeColor(Color(217, 217, 217));
         context->setStrokeThickness(1.0f);
-        context->setFillColor(Color::transparent, ColorSpaceDeviceRGB);
+        context->setFillColor(Color::transparent);
         context->drawRect(largerCorner);
     }
 }
@@ -3514,7 +3449,7 @@
 void RenderLayer::clipToRect(RenderLayer* rootLayer, GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect,
                              BorderRadiusClippingRule rule)
 {
-    if (clipRect.rect() == paintDirtyRect)
+    if (clipRect.rect() == paintDirtyRect && !clipRect.hasRadius())
         return;
     context->save();
     context->clip(pixelSnappedIntRect(clipRect.rect()));
@@ -3539,7 +3474,7 @@
 
 void RenderLayer::restoreClip(GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect)
 {
-    if (clipRect.rect() == paintDirtyRect)
+    if (clipRect.rect() == paintDirtyRect && !clipRect.hasRadius())
         return;
     context->restore();
 }
@@ -3583,8 +3518,7 @@
         // but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
         if (context->updatingControlTints() || (paintingInfo.paintBehavior & PaintBehaviorFlattenCompositingLayers))
             paintFlags |= PaintLayerTemporaryClipRects;
-        else if (!backing()->paintsIntoWindow()
-            && !backing()->paintsIntoCompositedAncestor()
+        else if (!backing()->paintsIntoCompositedAncestor()
             && !shouldDoSoftwarePaint(this, paintFlags & PaintLayerPaintingReflection)) {
             // If this RenderLayer should paint into its backing, that will be done via RenderLayerBacking::paintIntoLayer().
             return;
@@ -5496,8 +5430,7 @@
 
 bool RenderLayer::paintsWithTransform(PaintBehavior paintBehavior) const
 {
-    bool paintsToWindow = !isComposited() || backing()->paintsIntoWindow();
-    return transform() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || paintsToWindow);
+    return transform() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || !isComposited());
 }
 
 bool RenderLayer::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
@@ -5508,6 +5441,11 @@
     if (paintsWithTransparency(PaintBehaviorNormal))
         return false;
 
+    // We can't use hasVisibleContent(), because that will be true if our renderer is hidden, but some child
+    // is visible and that child doesn't cover the entire rect.
+    if (renderer()->style()->visibility() != VISIBLE)
+        return false;
+
     if (paintsWithFilters() && renderer()->style()->filter().hasFilterThatAffectsOpacity())
         return false;
 
@@ -5523,8 +5461,15 @@
 
     // FIXME: We currently only check the immediate renderer,
     // which will miss many cases.
-    return renderer()->backgroundIsKnownToBeOpaqueInRect(localRect)
-        || listBackgroundIsKnownToBeOpaqueInRect(posZOrderList(), localRect)
+    if (renderer()->backgroundIsKnownToBeOpaqueInRect(localRect))
+        return true;
+
+    // We can't consult child layers if we clip, since they might cover
+    // parts of the rect that are clipped out.
+    if (renderer()->hasOverflowClip())
+        return false;
+
+    return listBackgroundIsKnownToBeOpaqueInRect(posZOrderList(), localRect)
         || listBackgroundIsKnownToBeOpaqueInRect(negZOrderList(), localRect)
         || listBackgroundIsKnownToBeOpaqueInRect(normalFlowList(), localRect);
 }
@@ -5584,9 +5529,10 @@
         m_negZOrderList->clear();
     m_zOrderListsDirty = true;
 
-    m_descendantsAreContiguousInStackingOrderDirty = true;
+    m_canBePromotedToStackingContainerDirty = true;
 
     if (!renderer()->documentBeingDestroyed()) {
+        compositor()->setNeedsUpdateCompositingRequirementsState();
         compositor()->setCompositingLayersNeedRebuild();
         if (acceleratedCompositingForOverflowScrollEnabled())
             compositor()->setShouldReevaluateCompositingAfterLayout();
@@ -5628,16 +5574,16 @@
 {
     ASSERT(m_layerListMutationAllowed);
     ASSERT(isDirtyStackingContainer());
-    rebuildZOrderLists(StopAtStackingContainers, m_posZOrderList, m_negZOrderList);
+    rebuildZOrderLists(m_posZOrderList, m_negZOrderList);
     m_zOrderListsDirty = false;
 }
 
-void RenderLayer::rebuildZOrderLists(CollectLayersBehavior behavior, OwnPtr<Vector<RenderLayer*> >& posZOrderList, OwnPtr<Vector<RenderLayer*> >& negZOrderList, const RenderLayer* layerToForceAsStackingContainer)
+void RenderLayer::rebuildZOrderLists(OwnPtr<Vector<RenderLayer*> >& posZOrderList, OwnPtr<Vector<RenderLayer*> >& negZOrderList, const RenderLayer* layerToForceAsStackingContainer, CollectLayersBehavior collectLayersBehavior)
 {
     bool includeHiddenLayers = compositor()->inCompositingMode();
     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
         if (!m_reflection || reflectionLayer() != child)
-            child->collectLayers(includeHiddenLayers, behavior, posZOrderList, negZOrderList, layerToForceAsStackingContainer);
+            child->collectLayers(includeHiddenLayers, posZOrderList, negZOrderList, layerToForceAsStackingContainer, collectLayersBehavior);
 
     // Sort the two lists.
     if (posZOrderList)
@@ -5679,7 +5625,7 @@
     m_normalFlowListDirty = false;
 }
 
-void RenderLayer::collectLayers(bool includeHiddenLayers, CollectLayersBehavior behavior, OwnPtr<Vector<RenderLayer*> >& posBuffer, OwnPtr<Vector<RenderLayer*> >& negBuffer, const RenderLayer* layerToForceAsStackingContainer)
+void RenderLayer::collectLayers(bool includeHiddenLayers, OwnPtr<Vector<RenderLayer*> >& posBuffer, OwnPtr<Vector<RenderLayer*> >& negBuffer, const RenderLayer* layerToForceAsStackingContainer, CollectLayersBehavior collectLayersBehavior)
 {
     if (isInTopLayer())
         return;
@@ -5687,20 +5633,33 @@
     updateDescendantDependentFlags();
 
     bool isStacking = false;
+    bool isNormalFlow = false;
 
-    switch (behavior) {
-        case StopAtStackingContexts:
-            isStacking = (this == layerToForceAsStackingContainer) || isStackingContext();
-            break;
-
-        case StopAtStackingContainers:
-            isStacking = (this == layerToForceAsStackingContainer) || isStackingContainer();
-            break;
+    switch (collectLayersBehavior) {
+    case ForceLayerToStackingContainer:
+        ASSERT(layerToForceAsStackingContainer);
+        if (this == layerToForceAsStackingContainer) {
+            isStacking = true;
+            isNormalFlow = false;
+        } else {
+            isStacking = isStackingContext();
+            isNormalFlow = shouldBeNormalFlowOnlyIgnoringCompositedScrolling();
+        }
+        break;
+    case OverflowScrollCanBeStackingContainers:
+        ASSERT(!layerToForceAsStackingContainer);
+        isStacking = isStackingContainer();
+        isNormalFlow = isNormalFlowOnly();
+        break;
+    case OnlyStackingContextsCanBeStackingContainers:
+        isStacking = isStackingContext();
+        isNormalFlow = shouldBeNormalFlowOnlyIgnoringCompositedScrolling();
+        break;
     }
 
     // Overflow layers are just painted by their enclosing layers, so they don't get put in zorder lists.
     bool includeHiddenLayer = includeHiddenLayers || (m_hasVisibleContent || (m_hasVisibleDescendant && isStacking));
-    if (includeHiddenLayer && !isNormalFlowOnly() && !isOutOfFlowRenderFlowThread()) {
+    if (includeHiddenLayer && !isNormalFlow && !isOutOfFlowRenderFlowThread()) {
         // Determine which buffer the child should be in.
         OwnPtr<Vector<RenderLayer*> >& buffer = (zIndex() >= 0) ? posBuffer : negBuffer;
 
@@ -5718,14 +5677,13 @@
         for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
             // Ignore reflections.
             if (!m_reflection || reflectionLayer() != child)
-                child->collectLayers(includeHiddenLayers, behavior, posBuffer, negBuffer, layerToForceAsStackingContainer);
+                child->collectLayers(includeHiddenLayers, posBuffer, negBuffer, layerToForceAsStackingContainer, collectLayersBehavior);
         }
     }
 }
 
 void RenderLayer::updateLayerListsIfNeeded()
 {
-    bool shouldUpdateDescendantsAreContiguousInStackingOrder = acceleratedCompositingForOverflowScrollEnabled() && isStackingContext() && (m_zOrderListsDirty || m_normalFlowListDirty) && m_descendantsAreContiguousInStackingOrderDirty;
     updateZOrderLists();
     updateNormalFlowList();
 
@@ -5733,14 +5691,6 @@
         reflectionLayer->updateZOrderLists();
         reflectionLayer->updateNormalFlowList();
     }
-
-    if (shouldUpdateDescendantsAreContiguousInStackingOrder) {
-        updateDescendantsAreContiguousInStackingOrder();
-        // The above function can cause us to update m_needsCompositedScrolling
-        // and dirty our layer lists. Refresh them if necessary.
-        updateZOrderLists();
-        updateNormalFlowList();
-    }
 }
 
 void RenderLayer::repaintIncludingDescendants()
@@ -5753,14 +5703,7 @@
 void RenderLayer::setBackingNeedsRepaint()
 {
     ASSERT(isComposited());
-    if (backing()->paintsIntoWindow()) {
-        // If we're trying to repaint the placeholder document layer, propagate the
-        // repaint to the native view system.
-        RenderView* view = renderer()->view();
-        if (view)
-            view->repaintViewRectangle(absoluteBoundingBox());
-    } else
-        backing()->setContentsNeedDisplay();
+    backing()->setContentsNeedDisplay();
 }
 
 void RenderLayer::setBackingNeedsRepaintInRect(const LayoutRect& r)
@@ -5768,7 +5711,7 @@
     // https://bugs.webkit.org/show_bug.cgi?id=61159 describes an unreproducible crash here,
     // so assert but check that the layer is composited.
     ASSERT(isComposited());
-    if (!isComposited() || backing()->paintsIntoWindow()) {
+    if (!isComposited()) {
         // If we're trying to repaint the placeholder document layer, propagate the
         // repaint to the native view system.
         LayoutRect absRect(r);
@@ -5796,23 +5739,28 @@
 
 bool RenderLayer::shouldBeNormalFlowOnly() const
 {
-    return (renderer()->hasOverflowClip()
-                || renderer()->hasReflection()
-                || renderer()->hasMask()
-                || renderer()->isCanvas()
-                || renderer()->isVideo()
-                || renderer()->isEmbeddedObject()
-                || renderer()->isRenderIFrame()
-                || (renderer()->style()->specifiesColumns() && !isRootLayer()))
-            && !renderer()->isPositioned()
-            && !renderer()->hasTransform()
-            && !renderer()->hasClipPath()
-            && !renderer()->hasFilter()
-            && !renderer()->hasBlendMode()
-            && !isTransparent()
-            && !needsCompositedScrolling()
-            && !renderer()->isFloatingWithShapeOutside()
-            ;
+    return shouldBeNormalFlowOnlyIgnoringCompositedScrolling() && !needsCompositedScrolling();
+}
+
+bool RenderLayer::shouldBeNormalFlowOnlyIgnoringCompositedScrolling() const
+{
+    const bool couldBeNormalFlow = renderer()->hasOverflowClip()
+        || renderer()->hasReflection()
+        || renderer()->hasMask()
+        || renderer()->isCanvas()
+        || renderer()->isVideo()
+        || renderer()->isEmbeddedObject()
+        || renderer()->isRenderIFrame()
+        || (renderer()->style()->specifiesColumns() && !isRootLayer());
+    const bool preventsElementFromBeingNormalFlow = renderer()->isPositioned()
+        || renderer()->hasTransform()
+        || renderer()->hasClipPath()
+        || renderer()->hasFilter()
+        || renderer()->hasBlendMode()
+        || isTransparent()
+        || renderer()->isFloatingWithShapeOutside();
+
+    return couldBeNormalFlow && !preventsElementFromBeingNormalFlow;
 }
 
 void RenderLayer::updateIsNormalFlowOnly()
@@ -5911,14 +5859,8 @@
 
 void RenderLayer::updateVisibilityAfterStyleChange(const RenderStyle* oldStyle)
 {
-    EVisibility oldVisibility = oldStyle ? oldStyle->visibility() : VISIBLE;
-    if (oldVisibility == renderer()->style()->visibility() || !renderer()->isOutOfFlowPositioned())
-        return;
-
-    if (renderer()->style()->visibility() == VISIBLE)
-        setAncestorChainHasOutOfFlowPositionedDescendant(renderer()->containingBlock());
-    else
-        dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
+    if (!oldStyle || (oldStyle->visibility() != renderer()->style()->visibility()))
+        compositor()->setNeedsUpdateCompositingRequirementsState();
 }
 
 void RenderLayer::updateStackingContextsAfterStyleChange(const RenderStyle* oldStyle)
@@ -5940,7 +5882,7 @@
     else
         clearZOrderLists();
 
-    updateNeedsCompositedScrolling();
+    compositor()->setNeedsUpdateCompositingRequirementsState();
 }
 
 static bool overflowRequiresScrollbar(EOverflow overflow)
@@ -5989,45 +5931,34 @@
         updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
 }
 
-void RenderLayer::setAncestorChainHasOutOfFlowPositionedDescendant(RenderObject* containingBlock)
-{
-    for (RenderLayer* layer = this; layer; layer = layer->parent()) {
-        if (!layer->m_hasOutOfFlowPositionedDescendantDirty && layer->hasOutOfFlowPositionedDescendant())
-            break;
-
-        layer->m_hasOutOfFlowPositionedDescendantDirty = false;
-        layer->m_hasOutOfFlowPositionedDescendant = true;
-        layer->updateNeedsCompositedScrolling();
-
-        if (layer->renderer() && layer->renderer() == containingBlock)
-            break;
-    }
-}
-
-void RenderLayer::dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus()
-{
-    if (m_hasOutOfFlowPositionedDescendant) {
-        m_hasOutOfFlowPositionedDescendantDirty = true;
-        // FIXME It would be nice to avoid this when we clean up render layer
-        // updating. We shouldn't have to update the composited scrolling state
-        // nearly as frequently if all the updates happen in a single, well
-        // defined phase.
-        updateNeedsCompositedScrolling();
-    }
-
-    if (parent())
-        parent()->dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
-}
-
 void RenderLayer::updateOutOfFlowPositioned(const RenderStyle* oldStyle)
 {
+    if (oldStyle && (renderer()->style()->position() == oldStyle->position()))
+        return;
+
     bool wasOutOfFlowPositioned = oldStyle && (oldStyle->position() == AbsolutePosition || oldStyle->position() == FixedPosition);
     bool isOutOfFlowPositioned = renderer()->isOutOfFlowPositioned();
-    if (parent() && isOutOfFlowPositioned != wasOutOfFlowPositioned) {
-        if (isOutOfFlowPositioned)
-            parent()->setAncestorChainHasOutOfFlowPositionedDescendant(renderer()->containingBlock());
-        else
-            parent()->dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
+    if (!wasOutOfFlowPositioned && !isOutOfFlowPositioned)
+        return;
+
+    // Even if the layer remains out-of-flow, a change to this property
+    // will likely change its containing block. We must clear these bits
+    // so that they can be set properly by the RenderLayerCompositor.
+    for (RenderLayer* ancestor = parent(); ancestor; ancestor = ancestor->parent())
+        ancestor->setHasUnclippedDescendant(false);
+
+    // Ensures that we reset the above bits correctly.
+    compositor()->setNeedsUpdateCompositingRequirementsState();
+
+    if (wasOutOfFlowPositioned && isOutOfFlowPositioned)
+        return;
+
+    if (isOutOfFlowPositioned) {
+        setAncestorChainHasOutOfFlowPositionedDescendant();
+        compositor()->addOutOfFlowPositionedLayer(this);
+    } else {
+        dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
+        compositor()->removeOutOfFlowPositionedLayer(this);
     }
 }
 
@@ -6107,10 +6038,10 @@
 {
     updateIsNormalFlowOnly();
 
-    if (renderer()->style()->overflowX() == OMARQUEE && renderer()->style()->marqueeBehavior() != MNONE && renderer()->isBox()) {
+    if (renderer()->isHTMLMarquee() && renderer()->style()->marqueeBehavior() != MNONE && renderer()->isBox()) {
         if (!m_marquee)
             m_marquee = adoptPtr(new RenderMarquee(this));
-        UseCounter::count(renderer()->document(), renderer()->isHTMLMarquee() ? UseCounter::HTMLMarqueeElement : UseCounter::CSSOverflowMarquee);
+        UseCounter::count(renderer()->document(), UseCounter::HTMLMarqueeElement);
         m_marquee->updateMarqueeStyle();
     }
     else if (m_marquee) {
@@ -6193,14 +6124,13 @@
     if (HTMLFrameOwnerElement* owner = frame->ownerElement())
         isVisibleToHitTest &= owner->renderer() && owner->renderer()->visibleToHitTesting();
 
-    bool updatedScrollableAreaSet = false;
-    if (hasOverflow && isVisibleToHitTest)
-        updatedScrollableAreaSet = frameView->addScrollableArea(this);
-    else
-        updatedScrollableAreaSet = frameView->removeScrollableArea(this);
-
-    if (updatedScrollableAreaSet)
-        updateNeedsCompositedScrolling();
+    if (hasOverflow && isVisibleToHitTest) {
+        if (frameView->addScrollableArea(this))
+            compositor()->setNeedsUpdateCompositingRequirementsState();
+    } else {
+        if (frameView->removeScrollableArea(this))
+            setNeedsCompositedScrolling(false);
+    }
 }
 
 void RenderLayer::updateScrollCornerStyle()
diff --git a/Source/core/rendering/RenderLayer.h b/Source/core/rendering/RenderLayer.h
index 2b351ac..f1a0259 100644
--- a/Source/core/rendering/RenderLayer.h
+++ b/Source/core/rendering/RenderLayer.h
@@ -602,14 +602,16 @@
     // Part of the issue is with subtree relayout: we don't check if our ancestors have some descendant flags dirty, missing some updates.
     bool hasSelfPaintingLayerDescendant() const { return m_hasSelfPaintingLayerDescendant; }
 
-    // This returns true if we have an out of flow positioned descendant whose
-    // containing block is not a descendant of ours. If this is true, we cannot
-    // automatically opt into composited scrolling since this out of flow
-    // positioned descendant would become clipped by us, possibly altering the 
-    // rendering of the page.
-    // FIXME: We should ASSERT(!m_hasOutOfFlowPositionedDescendantDirty); here but we may hit the same bugs as visible content above.
+    // FIXME: We should ASSERT(!m_hasOutOfFlowPositionedDescendantDirty) here. See above.
     bool hasOutOfFlowPositionedDescendant() const { return m_hasOutOfFlowPositionedDescendant; }
 
+    void setHasOutOfFlowPositionedDescendant(bool hasDescendant) { m_hasOutOfFlowPositionedDescendant = hasDescendant; }
+    void setHasOutOfFlowPositionedDescendantDirty(bool dirty) { m_hasOutOfFlowPositionedDescendantDirty = dirty; }
+
+    bool hasUnclippedDescendant() const { return m_hasUnclippedDescendant; }
+    void setHasUnclippedDescendant(bool hasDescendant) { m_hasUnclippedDescendant = hasDescendant; }
+    void updateHasUnclippedDescendant();
+
     // Gets the nearest enclosing positioned ancestor layer (also includes
     // the <html> layer and the root layer).
     RenderLayer* enclosingPositionedAncestor() const;
@@ -867,13 +869,25 @@
     enum PaintOrderListType {BeforePromote, AfterPromote};
     void computePaintOrderList(PaintOrderListType type, Vector<RefPtr<Node> >&);
 
+    enum ForceNeedsCompositedScrollingMode {
+        DoNotForceCompositedScrolling = 0,
+        CompositedScrollingAlwaysOn = 1,
+        CompositedScrollingAlwaysOff = 2
+    };
+
+    void setForceNeedsCompositedScrolling(ForceNeedsCompositedScrollingMode);
+
 private:
-    enum CollectLayersBehavior { StopAtStackingContexts, StopAtStackingContainers };
+    enum CollectLayersBehavior {
+        ForceLayerToStackingContainer,
+        OverflowScrollCanBeStackingContainers,
+        OnlyStackingContextsCanBeStackingContainers
+    };
 
     void updateZOrderLists();
     void rebuildZOrderLists();
     // See the comment for collectLayers for information about the layerToForceAsStackingContainer parameter.
-    void rebuildZOrderLists(CollectLayersBehavior, OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&, const RenderLayer* layerToForceAsStackingContainer = 0);
+    void rebuildZOrderLists(OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&, const RenderLayer* layerToForceAsStackingContainer = 0, CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
     void clearZOrderLists();
 
     void updateNormalFlowList();
@@ -885,9 +899,11 @@
     void setAncestorChainHasSelfPaintingLayerDescendant();
     void dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
 
+    void setAncestorChainHasOutOfFlowPositionedDescendant();
+    void dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
+
     bool acceleratedCompositingForOverflowScrollEnabled() const;
-    void updateDescendantsAreContiguousInStackingOrder();
-    void updateDescendantsAreContiguousInStackingOrderRecursive(const HashMap<const RenderLayer*, int>&, int& minIndex, int& maxIndex, int& count, bool firstIteration);
+    void updateCanBeStackingContainer();
     void collectBeforePromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListBeforePromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListBeforePromote);
     void collectAfterPromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListAfterPromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListAfterPromote);
 
@@ -909,11 +925,11 @@
     void updateScrollbarsAfterStyleChange(const RenderStyle* oldStyle);
     void updateScrollbarsAfterLayout();
 
-    void setAncestorChainHasOutOfFlowPositionedDescendant(RenderObject* containingBlock);
-    void dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
     void updateOutOfFlowPositioned(const RenderStyle* oldStyle);
 
-    void updateNeedsCompositedScrolling();
+    virtual void updateNeedsCompositedScrolling() OVERRIDE;
+    void setNeedsCompositedScrolling(bool);
+    void didUpdateNeedsCompositedScrolling();
 
     // Returns true if the position changed.
     bool updateLayerPosition();
@@ -950,7 +966,7 @@
     // post-promotion layer lists, by allowing us to treat a layer as if it is a
     // stacking context, without adding a new member to RenderLayer or modifying
     // the style (which could cause extra allocations).
-    void collectLayers(bool includeHiddenLayers, CollectLayersBehavior, OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&, const RenderLayer* layerToForceAsStackingContainer = 0);
+    void collectLayers(bool includeHiddenLayers, OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&, const RenderLayer* layerToForceAsStackingContainer = 0, CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
 
     struct LayerPaintingInfo {
         LayerPaintingInfo(RenderLayer* inRootLayer, const LayoutRect& inDirtyRect, PaintBehavior inPaintBehavior, const LayoutSize& inSubPixelAccumulation, RenderObject* inPaintingRoot = 0, RenderRegion*inRegion = 0, OverlapTestRequestMap* inOverlapTestRequests = 0)
@@ -1034,6 +1050,7 @@
     bool hasScrollableVerticalOverflow() const;
 
     bool shouldBeNormalFlowOnly() const;
+    bool shouldBeNormalFlowOnlyIgnoringCompositedScrolling() const;
 
     bool shouldBeSelfPaintingLayer() const;
 
@@ -1077,7 +1094,7 @@
     void dirtyAncestorChainVisibleDescendantStatus();
     void setAncestorChainHasVisibleDescendant();
 
-    void updateDescendantDependentFlags(HashSet<const RenderObject*>* outOfFlowDescendantContainingBlocks = 0);
+    void updateDescendantDependentFlags();
 
     // This flag is computed by RenderLayerCompositor, which knows more about 3d hierarchies than we do.
     void setHas3DTransformedDescendant(bool b) { m_has3DTransformedDescendant = b; }
@@ -1165,19 +1182,22 @@
     bool m_hasSelfPaintingLayerDescendant : 1;
     bool m_hasSelfPaintingLayerDescendantDirty : 1;
 
-    // If we have no out of flow positioned descendants and no non-descendant
-    // appears between our descendants in stacking order, then we may become a
-    // stacking context.
     bool m_hasOutOfFlowPositionedDescendant : 1;
     bool m_hasOutOfFlowPositionedDescendantDirty : 1;
 
+    // This is true if we have an out-of-flow positioned descendant whose
+    // containing block is our ancestor. If this is the case, the descendant
+    // may fall outside of our clip preventing things like opting into
+    // composited scrolling (which causes clipping of all descendants).
+    bool m_hasUnclippedDescendant : 1;
+
     bool m_needsCompositedScrolling : 1;
 
     // If this is true, then no non-descendant appears between any of our
     // descendants in stacking order. This is one of the requirements of being
     // able to safely become a stacking context.
-    bool m_descendantsAreContiguousInStackingOrder : 1;
-    bool m_descendantsAreContiguousInStackingOrderDirty : 1;
+    bool m_canBePromotedToStackingContainer : 1;
+    bool m_canBePromotedToStackingContainerDirty : 1;
 
     const bool m_isRootLayer : 1;
 
@@ -1259,7 +1279,7 @@
     
     IntPoint m_cachedOverlayScrollbarOffset;
 
-    OwnPtr<RenderMarquee> m_marquee; // Used by layers with overflow:marquee
+    OwnPtr<RenderMarquee> m_marquee; // Used for <marquee>.
     
     // Cached normal flow values for absolute positioned elements with static left/top values.
     LayoutUnit m_staticInlinePosition;
@@ -1298,6 +1318,8 @@
 
     CompositingProperties m_compositingProperties;
 
+    ForceNeedsCompositedScrollingMode m_forceNeedsCompositedScrolling;
+
 private:
     IntRect m_blockSelectionGapsBounds;
 
diff --git a/Source/core/rendering/RenderLayerBacking.cpp b/Source/core/rendering/RenderLayerBacking.cpp
index d796473..a5a84c2 100644
--- a/Source/core/rendering/RenderLayerBacking.cpp
+++ b/Source/core/rendering/RenderLayerBacking.cpp
@@ -29,7 +29,7 @@
 
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
-#include "core/css/resolver/StyleResolver.h"
+#include "RuntimeEnabledFeatures.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/html/HTMLCanvasElement.h"
 #include "core/html/HTMLIFrameElement.h"
@@ -195,8 +195,10 @@
     
     m_graphicsLayer = createGraphicsLayer(layerName, m_owningLayer->compositingReasons());
 
+#if !OS(ANDROID)
     if (m_isMainFrameRenderViewLayer)
-        m_graphicsLayer->setContentsOpaque(true);
+        m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
+#endif
 
     updateOpacity(renderer()->style());
     updateTransform(renderer()->style());
@@ -268,6 +270,13 @@
 {
 }
 
+void RenderLayerBacking::updateContentsOpaque()
+{
+    // For non-root layers, background is always painted by the primary graphics layer.
+    ASSERT(m_isMainFrameRenderViewLayer || !m_backgroundLayer);
+    m_graphicsLayer->setContentsOpaque(m_owningLayer->backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
+}
+
 static bool hasNonZeroTransformOrigin(const RenderObject* renderer)
 {
     RenderStyle* style = renderer->style();
@@ -379,7 +388,7 @@
         }
     }
     
-    if (flags & NeedsFullRepaint && !paintsIntoWindow() && !paintsIntoCompositedAncestor())
+    if (flags & NeedsFullRepaint && !paintsIntoCompositedAncestor())
         setContentsNeedDisplay();
 }
 
@@ -572,11 +581,6 @@
         if (m_boundsConstrainedByClipping)
             m_graphicsLayer->setNeedsDisplay();
     }
-    if (!m_isMainFrameRenderViewLayer) {
-        // For non-root layers, background is always painted by the primary graphics layer.
-        ASSERT(!m_backgroundLayer);
-        m_graphicsLayer->setContentsOpaque(m_owningLayer->backgroundIsKnownToBeOpaqueInRect(localCompositingBounds));
-    }
 
     // If we have a layer that clips children, position it.
     IntRect clippingBox;
@@ -726,6 +730,7 @@
     updateContentsRect(isSimpleContainer);
     updateBackgroundColor(isSimpleContainer);
     updateDrawsContent(isSimpleContainer);
+    updateContentsOpaque();
     updateAfterWidgetResize();
     registerScrollingLayers();
 
@@ -1330,7 +1335,7 @@
 
 bool RenderLayerBacking::containsPaintedContent() const
 {
-    if (isSimpleContainerCompositingLayer() || paintsIntoWindow() || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer->isReflection())
+    if (isSimpleContainerCompositingLayer() || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer->isReflection())
         return false;
 
     if (isDirectlyCompositedImage())
@@ -1513,15 +1518,6 @@
     return m_graphicsLayer.get();
 }
 
-bool RenderLayerBacking::paintsIntoWindow() const
-{
-    if (m_owningLayer->isRootLayer()) {
-        return compositor()->rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingFrame;
-    }
-    
-    return false;
-}
-
 void RenderLayerBacking::setRequiresOwnBackingStore(bool requiresOwnBacking)
 {
     if (requiresOwnBacking == m_requiresOwnBackingStore)
@@ -1602,7 +1598,7 @@
                     const IntRect& paintDirtyRect, // In the coords of rootLayer.
                     PaintBehavior paintBehavior, GraphicsLayerPaintingPhase paintingPhase)
 {
-    if (paintsIntoWindow() || paintsIntoCompositedAncestor()) {
+    if (paintsIntoCompositedAncestor()) {
         ASSERT_NOT_REACHED();
         return;
     }
diff --git a/Source/core/rendering/RenderLayerBacking.h b/Source/core/rendering/RenderLayerBacking.h
index 15bf171..e4efc64 100644
--- a/Source/core/rendering/RenderLayerBacking.h
+++ b/Source/core/rendering/RenderLayerBacking.h
@@ -72,7 +72,9 @@
     void updateGraphicsLayerGeometry(); // make private
     // Update contents and clipping structure.
     void updateDrawsContent();
-    
+    // Update whether layer needs blending.
+    void updateContentsOpaque();
+
     GraphicsLayer* graphicsLayer() const { return m_graphicsLayer.get(); }
 
     // Layer to clip children
@@ -100,14 +102,6 @@
     GraphicsLayer* parentForSublayers() const;
     GraphicsLayer* childForSuperlayers() const;
 
-    // RenderLayers with backing normally short-circuit paintLayer() because
-    // their content is rendered via callbacks from GraphicsLayer. However, the document
-    // layer is special, because it has a GraphicsLayer to act as a container for the GraphicsLayers
-    // for descendants, but its contents usually render into the window (in which case this returns true).
-    // This returns false for other layers, and when the document layer actually needs to paint into its backing store
-    // for some reason.
-    bool paintsIntoWindow() const;
-    
     // Returns true for a composited layer that has no backing store of its own, so
     // paints into some ancestor layer.
     bool paintsIntoCompositedAncestor() const { return !m_requiresOwnBackingStore; }
diff --git a/Source/core/rendering/RenderLayerCompositor.cpp b/Source/core/rendering/RenderLayerCompositor.cpp
index 4b2c4d0..8dfcfe8 100644
--- a/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/RenderLayerCompositor.cpp
@@ -218,6 +218,7 @@
     , m_compositingLayersNeedRebuild(false)
     , m_forceCompositingMode(false)
     , m_inPostLayoutUpdate(false)
+    , m_needsUpdateCompositingRequirementsState(false)
     , m_isTrackingRepaints(false)
     , m_rootLayerAttachment(RootLayerUnattached)
 #if !LOG_DISABLED
@@ -330,6 +331,29 @@
     return m_compositedLayerCount > (rootLayer->isComposited() ? 1 : 0);
 }
 
+void RenderLayerCompositor::updateCompositingRequirementsState()
+{
+    TRACE_EVENT0("blink_rendering", "RenderLayerCompositor::updateCompositingRequirementsState");
+
+    if (!m_needsUpdateCompositingRequirementsState)
+        return;
+
+    m_needsUpdateCompositingRequirementsState = false;
+
+    if (!rootRenderLayer() || !rootRenderLayer()->acceleratedCompositingForOverflowScrollEnabled())
+        return;
+
+    const FrameView::ScrollableAreaSet* scrollableAreas = m_renderView->frameView()->scrollableAreas();
+    if (!scrollableAreas)
+        return;
+
+    for (HashSet<RenderLayer*>::iterator it = m_outOfFlowPositionedLayers.begin(); it != m_outOfFlowPositionedLayers.end(); ++it)
+        (*it)->updateHasUnclippedDescendant();
+
+    for (FrameView::ScrollableAreaSet::iterator it = scrollableAreas->begin(); it != scrollableAreas->end(); ++it)
+        (*it)->updateNeedsCompositedScrolling();
+}
+
 void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
 {
     // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
@@ -492,6 +516,16 @@
 }
 #endif
 
+void RenderLayerCompositor::addOutOfFlowPositionedLayer(RenderLayer* layer)
+{
+    m_outOfFlowPositionedLayers.add(layer);
+}
+
+void RenderLayerCompositor::removeOutOfFlowPositionedLayer(RenderLayer* layer)
+{
+    m_outOfFlowPositionedLayers.remove(layer);
+}
+
 bool RenderLayerCompositor::updateBacking(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
 {
     bool layerChanged = false;
@@ -1142,10 +1176,8 @@
     // If there's a scrolling coordinator that manages scrolling for this frame view,
     // it will also manage updating the scroll layer position.
     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
-        if (scrollingCoordinator->coordinatesScrollingForFrameView(frameView))
-            return;
         if (Settings* settings = m_renderView->document()->settings()) {
-            if (settings->compositedScrollingForFramesEnabled())
+            if (isMainFrame() || settings->compositedScrollingForFramesEnabled())
                 scrollingCoordinator->scrollableAreaScrollLayerDidChange(frameView);
         }
     }
@@ -1509,7 +1541,6 @@
     RenderObject* renderer = layer->renderer();
     if (compositingAncestorLayer
         && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
-            || compositingAncestorLayer->backing()->paintsIntoWindow()
             || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
         return true;
 
@@ -2483,7 +2514,6 @@
     }
 
     m_rootLayerAttachment = attachment;
-    rootLayerAttachmentChanged();
 }
 
 void RenderLayerCompositor::detachRootLayer()
@@ -2518,7 +2548,6 @@
     }
 
     m_rootLayerAttachment = RootLayerUnattached;
-    rootLayerAttachmentChanged();
 }
 
 void RenderLayerCompositor::updateRootLayerAttachment()
@@ -2531,15 +2560,6 @@
     return !m_renderView->document()->ownerElement();
 }
 
-void RenderLayerCompositor::rootLayerAttachmentChanged()
-{
-    // The attachment can affect whether the RenderView layer's paintsIntoWindow() behavior,
-    // so call updateGraphicsLayerGeometry() to udpate that.
-    RenderLayer* layer = m_renderView->layer();
-    if (RenderLayerBacking* backing = layer ? layer->backing() : 0)
-        backing->updateDrawsContent();
-}
-
 // IFrames are special, because we hook compositing layers together across iframe boundaries
 // when both parent and iframe content are composited. So when this frame becomes composited, we have
 // to use a synthetic style change to get the iframes into RenderLayers in order to allow them to composite.
diff --git a/Source/core/rendering/RenderLayerCompositor.h b/Source/core/rendering/RenderLayerCompositor.h
index 15f73f5..00087e0 100644
--- a/Source/core/rendering/RenderLayerCompositor.h
+++ b/Source/core/rendering/RenderLayerCompositor.h
@@ -87,7 +87,11 @@
 
     // Called when something outside WebKit affects the visible rect (e.g. delegated scrolling). Might schedule a layer flush.
     void didChangeVisibleRect();
-    
+
+    // Updating properties required for determining if compositing is necessary.
+    void updateCompositingRequirementsState();
+    void setNeedsUpdateCompositingRequirementsState() { m_needsUpdateCompositingRequirementsState = true; }
+
     // Rebuild the tree of compositing layers
     void updateCompositingLayers(CompositingUpdateType, RenderLayer* updateRoot = 0);
     
@@ -190,6 +194,9 @@
     void updateViewportConstraintStatus(RenderLayer*);
     void removeViewportConstrainedLayer(RenderLayer*);
 
+    void addOutOfFlowPositionedLayer(RenderLayer*);
+    void removeOutOfFlowPositionedLayer(RenderLayer*);
+
     void resetTrackedRepaintRects();
     void setTracksRepaints(bool);
 
@@ -258,8 +265,6 @@
 
     bool isMainFrame() const;
     
-    void rootLayerAttachmentChanged();
-
     void updateOverflowControlsLayers();
 
     void notifyIFramesOfCompositingChange();
@@ -322,6 +327,7 @@
     bool m_compositingLayersNeedRebuild;
     bool m_forceCompositingMode;
     bool m_inPostLayoutUpdate; // true when it's OK to trust layout information (e.g. layer sizes and positions)
+    bool m_needsUpdateCompositingRequirementsState;
 
     bool m_isTrackingRepaints; // Used for testing.
     
@@ -334,6 +340,10 @@
     HashSet<RenderLayer*> m_viewportConstrainedLayers;
     HashSet<RenderLayer*> m_viewportConstrainedLayersNeedingUpdate;
 
+    // This is used in updateCompositingRequirementsState to avoid full tree
+    // walks while determining if layers have unclipped descendants.
+    HashSet<RenderLayer*> m_outOfFlowPositionedLayers;
+
     // Enclosing layer for overflow controls and the clipping layer
     OwnPtr<GraphicsLayer> m_overflowControlsHostLayer;
 
diff --git a/Source/core/rendering/RenderListBox.cpp b/Source/core/rendering/RenderListBox.cpp
index 5ecfdef..6ebf5ef 100644
--- a/Source/core/rendering/RenderListBox.cpp
+++ b/Source/core/rendering/RenderListBox.cpp
@@ -416,8 +416,7 @@
             textColor = theme()->inactiveListBoxSelectionForegroundColor();
     }
 
-    ColorSpace colorSpace = itemStyle->colorSpace();
-    paintInfo.context->setFillColor(textColor, colorSpace);
+    paintInfo.context->setFillColor(textColor);
 
     TextRun textRun(itemText, 0, 0, TextRun::AllowTrailingExpansion, itemStyle->direction(), isOverride(itemStyle->unicodeBidi()), true, TextRun::NoRounding);
     Font itemFont = style()->font();
@@ -453,10 +452,9 @@
 
     // Draw the background for this list box item
     if (!element->renderStyle() || element->renderStyle()->visibility() != HIDDEN) {
-        ColorSpace colorSpace = element->renderStyle() ? element->renderStyle()->colorSpace() : style()->colorSpace();
         LayoutRect itemRect = itemBoundingBoxRect(paintOffset, listIndex);
         itemRect.intersect(controlClipRect(paintOffset));
-        paintInfo.context->fillRect(pixelSnappedIntRect(itemRect), backColor, colorSpace);
+        paintInfo.context->fillRect(pixelSnappedIntRect(itemRect), backColor);
     }
 }
 
@@ -836,6 +834,11 @@
     return view->frameView()->scrollbarsCanBeActive();
 }
 
+IntPoint RenderListBox::maximumScrollPosition() const
+{
+    return IntPoint(0, numItems() - numVisibleItems());
+}
+
 ScrollableArea* RenderListBox::enclosingScrollableArea() const
 {
     // FIXME: Return a RenderLayer that's scrollable.
diff --git a/Source/core/rendering/RenderListBox.h b/Source/core/rendering/RenderListBox.h
index 43c47db..1b53fda 100644
--- a/Source/core/rendering/RenderListBox.h
+++ b/Source/core/rendering/RenderListBox.h
@@ -121,6 +121,7 @@
     virtual IntPoint lastKnownMousePosition() const OVERRIDE;
     virtual bool shouldSuspendScrollAnimations() const OVERRIDE;
     virtual bool scrollbarsCanBeActive() const OVERRIDE;
+    virtual IntPoint maximumScrollPosition() const OVERRIDE;
 
     virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
     virtual IntRect scrollableAreaBoundingBox() const OVERRIDE;
diff --git a/Source/core/rendering/RenderListItem.cpp b/Source/core/rendering/RenderListItem.cpp
index f6782e4..fd91115 100644
--- a/Source/core/rendering/RenderListItem.cpp
+++ b/Source/core/rendering/RenderListItem.cpp
@@ -358,7 +358,6 @@
                     hitSelfPaintingLayer = true;
             }
         } else {
-            markerLogicalLeft = m_marker->logicalLeft() + paddingStart() + borderStart() + m_marker->marginEnd();
             LayoutUnit rightLineOffset = logicalRightOffsetForLine(blockOffset, logicalRightOffsetForLine(blockOffset, false), false);
             markerLogicalLeft = rightLineOffset - lineOffset + paddingStart() + borderStart() + m_marker->marginEnd();
             m_marker->inlineBoxWrapper()->adjustLineDirectionPosition(markerLogicalLeft - markerOldLogicalLeft);
diff --git a/Source/core/rendering/RenderListMarker.cpp b/Source/core/rendering/RenderListMarker.cpp
index f7bcaf6..092f8f4 100644
--- a/Source/core/rendering/RenderListMarker.cpp
+++ b/Source/core/rendering/RenderListMarker.cpp
@@ -1124,9 +1124,11 @@
 
 void RenderListMarker::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     if (paintInfo.phase != PaintPhaseForeground)
         return;
-    
+
     if (style()->visibility() != VISIBLE)
         return;
 
@@ -1139,18 +1141,18 @@
         return;
 
     LayoutRect box(boxOrigin, size());
-    
+
     IntRect marker = getRelativeMarkerRect();
     marker.moveBy(roundedIntPoint(boxOrigin));
 
     GraphicsContext* context = paintInfo.context;
 
     if (isImage()) {
-        context->drawImage(m_image->image(this, marker.size()).get(), style()->colorSpace(), marker);
+        context->drawImage(m_image->image(this, marker.size()).get(), marker);
         if (selectionState() != SelectionNone) {
             LayoutRect selRect = localSelectionRect();
             selRect.moveBy(boxOrigin);
-            context->fillRect(pixelSnappedIntRect(selRect), selectionBackgroundColor(), style()->colorSpace());
+            context->fillRect(pixelSnappedIntRect(selRect), selectionBackgroundColor());
         }
         return;
     }
@@ -1158,14 +1160,14 @@
     if (selectionState() != SelectionNone) {
         LayoutRect selRect = localSelectionRect();
         selRect.moveBy(boxOrigin);
-        context->fillRect(pixelSnappedIntRect(selRect), selectionBackgroundColor(), style()->colorSpace());
+        context->fillRect(pixelSnappedIntRect(selRect), selectionBackgroundColor());
     }
 
     const Color color(style()->visitedDependentColor(CSSPropertyColor));
-    context->setStrokeColor(color, style()->colorSpace());
+    context->setStrokeColor(color);
     context->setStrokeStyle(SolidStroke);
     context->setStrokeThickness(1.0f);
-    context->setFillColor(color, style()->colorSpace());
+    context->setFillColor(color);
 
     EListStyleType type = style()->listStyleType();
     switch (type) {
diff --git a/Source/core/rendering/RenderMarquee.h b/Source/core/rendering/RenderMarquee.h
index ce69255..01c5d64 100644
--- a/Source/core/rendering/RenderMarquee.h
+++ b/Source/core/rendering/RenderMarquee.h
@@ -52,7 +52,7 @@
 
 class RenderLayer;
 
-// This class handles the auto-scrolling of layers with overflow: marquee.
+// This class handles the auto-scrolling for <marquee>
 class RenderMarquee {
     WTF_MAKE_NONCOPYABLE(RenderMarquee); WTF_MAKE_FAST_ALLOCATED;
 public:
diff --git a/Source/core/rendering/RenderMediaControlsChromium.cpp b/Source/core/rendering/RenderMediaControlsChromium.cpp
index fc20dcc..f08f4ce 100644
--- a/Source/core/rendering/RenderMediaControlsChromium.cpp
+++ b/Source/core/rendering/RenderMediaControlsChromium.cpp
@@ -61,7 +61,7 @@
 
 static bool paintMediaButton(GraphicsContext* context, const IntRect& rect, Image* image)
 {
-    context->drawImage(image, ColorSpaceDeviceRGB, rect);
+    context->drawImage(image, rect);
     return true;
 }
 
@@ -133,7 +133,7 @@
     IntSize radii(borderRadius, borderRadius);
     Color sliderBackgroundColor = Color(11, 11, 11);
     context->save();
-    context->fillRoundedRect(rect, radii, radii, radii, radii, sliderBackgroundColor, ColorSpaceDeviceRGB);
+    context->fillRoundedRect(rect, radii, radii, radii, radii, sliderBackgroundColor);
     context->restore();
 }
 
@@ -182,11 +182,11 @@
     context->setFillGradient(gradient);
 
     if (startOffset < borderRadius && endOffset < borderRadius)
-        context->fillRoundedRect(highlightRect, radii, radii, radii, radii, startColor, ColorSpaceDeviceRGB);
+        context->fillRoundedRect(highlightRect, radii, radii, radii, radii, startColor);
     else if (startOffset < borderRadius)
-        context->fillRoundedRect(highlightRect, radii, IntSize(0, 0), radii, IntSize(0, 0), startColor, ColorSpaceDeviceRGB);
+        context->fillRoundedRect(highlightRect, radii, IntSize(0, 0), radii, IntSize(0, 0), startColor);
     else if (endOffset < borderRadius)
-        context->fillRoundedRect(highlightRect, IntSize(0, 0), radii, IntSize(0, 0), radii, startColor, ColorSpaceDeviceRGB);
+        context->fillRoundedRect(highlightRect, IntSize(0, 0), radii, IntSize(0, 0), radii, startColor);
     else
         context->fillRect(highlightRect);
 
@@ -380,8 +380,6 @@
     case MediaTextTrackDisplay:
     case MediaFullScreenVolumeSlider:
     case MediaFullScreenVolumeSliderThumb:
-    case MediaClosedCaptionsContainer:
-    case MediaClosedCaptionsTrackList:
         ASSERT_NOT_REACHED();
         break;
     }
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index 83bb6dd..89266ab 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -915,7 +915,7 @@
                 bool wasAntialiased = graphicsContext->shouldAntialias();
                 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
                 graphicsContext->setShouldAntialias(antialias);
-                graphicsContext->setStrokeColor(color, m_style->colorSpace());
+                graphicsContext->setStrokeColor(color);
                 graphicsContext->setStrokeThickness(thickness);
                 graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
 
@@ -941,8 +941,8 @@
             if (adjacentWidth1 == 0 && adjacentWidth2 == 0) {
                 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
                 graphicsContext->setStrokeStyle(NoStroke);
-                graphicsContext->setFillColor(color, m_style->colorSpace());
-                
+                graphicsContext->setFillColor(color);
+
                 bool wasAntialiased = graphicsContext->shouldAntialias();
                 graphicsContext->setShouldAntialias(antialias);
 
@@ -1063,7 +1063,7 @@
         case SOLID: {
             StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
             graphicsContext->setStrokeStyle(NoStroke);
-            graphicsContext->setFillColor(color, m_style->colorSpace());
+            graphicsContext->setFillColor(color);
             ASSERT(x2 >= x1);
             ASSERT(y2 >= y1);
             if (!adjacentWidth1 && !adjacentWidth2) {
@@ -1184,7 +1184,7 @@
             path.addRect(outer);
             path.addRect(inner);
             graphicsContext->setFillRule(RULE_EVENODD);
-            graphicsContext->setFillColor(outlineColor, styleToUse->colorSpace());
+            graphicsContext->setFillColor(outlineColor);
             graphicsContext->fillPath(path);
             return;
         }
@@ -1359,7 +1359,7 @@
     if (repaintContainer->isRenderView()) {
         ASSERT(repaintContainer == v);
         bool viewHasCompositedLayer = v->hasLayer() && v->layer()->isComposited();
-        if (!viewHasCompositedLayer || v->layer()->backing()->paintsIntoWindow()) {
+        if (!viewHasCompositedLayer) {
             LayoutRect repaintRectangle = r;
             if (viewHasCompositedLayer &&  v->layer()->transform())
                 repaintRectangle = enclosingIntRect(v->layer()->transform()->mapRect(r));
@@ -1801,6 +1801,20 @@
     setStyle(pseudoStyle);
 }
 
+inline bool RenderObject::hasImmediateNonWhitespaceTextChild() const
+{
+    for (const RenderObject* r = firstChild(); r; r = r->nextSibling()) {
+        if (r->isText() && !toRenderText(r)->isAllCollapsibleWhitespace())
+            return true;
+    }
+    return false;
+}
+
+inline bool RenderObject::shouldRepaintForStyleDifference(StyleDifference diff) const
+{
+    return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfText && hasImmediateNonWhitespaceTextChild());
+}
+
 void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
 {
     if (m_style == style) {
@@ -1860,7 +1874,7 @@
             setNeedsSimplifiedNormalFlowLayout();
     }
     
-    if (updatedDiff == StyleDifferenceRepaintLayer || updatedDiff == StyleDifferenceRepaint) {
+    if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
         // Do a repaint with the new style now, e.g., for example if we go from
         // not having an outline to having an outline.
         repaint();
@@ -1901,7 +1915,7 @@
             }
         }
 
-        if (m_parent && (diff == StyleDifferenceRepaint || newStyle->outlineSize() < m_style->outlineSize()))
+        if (m_parent && (newStyle->outlineSize() < m_style->outlineSize() || shouldRepaintForStyleDifference(diff)))
             repaint();
         if (isFloating() && (m_style->floating() != newStyle->floating()))
             // For changes in float styles, we need to conceivably remove ourselves
@@ -2399,8 +2413,8 @@
     // has a null frame, so we assert this. However, we don't want release builds to crash which is why we
     // check that the frame is not null.
     ASSERT(frame());
-    if (frame() && frame()->eventHandler()->autoscrollRenderer() == this)
-        frame()->eventHandler()->stopAutoscrollTimer(true);
+    if (frame() && frame()->page())
+        frame()->page()->stopAutoscrollIfNeeded(this);
 
     animation()->cancelAnimations(this);
 
@@ -2796,12 +2810,10 @@
 static Color decorationColor(RenderStyle* style)
 {
     Color result;
-#if ENABLE(CSS3_TEXT)
     // Check for text decoration color first.
-    result = style->visitedDependentColor(CSSPropertyWebkitTextDecorationColor);
+    result = style->visitedDependentColor(CSSPropertyTextDecorationColor);
     if (result.isValid())
         return result;
-#endif // CSS3_TEXT
     if (style->textStrokeWidth() > 0) {
         // Prefer stroke color if possible but not if it's fully transparent.
         result = style->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
@@ -2956,11 +2968,50 @@
     return frame()->animation();
 }
 
+bool RenderObject::isInert() const
+{
+    const RenderObject* renderer = this;
+    while (!renderer->node())
+        renderer = renderer->parent();
+    const Node* parentNode = renderer->node();
+    while (parentNode && !parentNode->isElementNode())
+        parentNode = parentNode->parentNode();
+    return parentNode && toElement(parentNode)->isInert();
+}
+
 void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
 {
     imageChanged(static_cast<WrappedImagePtr>(image), rect);
 }
 
+RenderObject* RenderObject::hoverAncestor() const
+{
+    // When searching for the hover ancestor and encountering a named flow thread,
+    // the search will continue with the DOM ancestor of the top-most element
+    // in the named flow thread.
+    // See https://code.google.com/p/chromium/issues/detail?id=243278
+    RenderObject* hoverAncestor = parent();
+
+    // Skip anonymous blocks. There's no point in treating them as hover ancestors
+    // and it would also prevent us from continuing the search on the DOM tree
+    // when reaching the named flow thread.
+    if (hoverAncestor && hoverAncestor->isAnonymousBlock())
+        hoverAncestor = hoverAncestor->parent();
+
+    if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
+        hoverAncestor = 0;
+
+        Node* node = this->node();
+        if (node) {
+            Node* domAncestorNode = node->parentNode();
+            if (domAncestorNode)
+                hoverAncestor = domAncestorNode->renderer();
+        }
+    }
+
+    return hoverAncestor;
+}
+
 Element* RenderObject::offsetParent() const
 {
     if (isRoot() || isBody())
diff --git a/Source/core/rendering/RenderObject.h b/Source/core/rendering/RenderObject.h
index 4880b30..2eb0b10 100644
--- a/Source/core/rendering/RenderObject.h
+++ b/Source/core/rendering/RenderObject.h
@@ -623,7 +623,7 @@
     // is true if the renderer returned is an ancestor of repaintContainer.
     RenderObject* container(const RenderLayerModelObject* repaintContainer = 0, bool* repaintContainerSkipped = 0) const;
 
-    virtual RenderObject* hoverAncestor() const { return parent(); }
+    virtual RenderObject* hoverAncestor() const;
 
     Element* offsetParent() const;
 
@@ -919,7 +919,7 @@
 
     AnimationController* animation() const;
 
-    bool isInert() const { return node() && node()->isElementNode() && toElement(node())->isInert(); }
+    bool isInert() const;
     bool visibleToHitTestRequest(const HitTestRequest& request) const { return style()->visibility() == VISIBLE && (request.ignorePointerEventsNone() || style()->pointerEvents() != PE_NONE) && !isInert(); }
     bool visibleToHitTesting() const { return style()->visibility() == VISIBLE && style()->pointerEvents() != PE_NONE && !isInert(); }
 
@@ -986,6 +986,9 @@
     void removeFromRenderFlowThread();
     void removeFromRenderFlowThreadRecursive(RenderFlowThread*);
 
+    bool shouldRepaintForStyleDifference(StyleDifference) const;
+    bool hasImmediateNonWhitespaceTextChild() const;
+
     RenderStyle* cachedFirstLineStyle() const;
     StyleDifference adjustStyleDifference(StyleDifference, unsigned contextSensitiveProperties) const;
 
diff --git a/Source/core/rendering/RenderRegion.cpp b/Source/core/rendering/RenderRegion.cpp
index dc1d6b4..071a20b 100644
--- a/Source/core/rendering/RenderRegion.cpp
+++ b/Source/core/rendering/RenderRegion.cpp
@@ -92,7 +92,7 @@
     return overflowRectForFlowThreadPortion(flowThreadPortionRect(), isFirstRegion(), isLastRegion());
 }
 
-LayoutRect RenderRegion::overflowRectForFlowThreadPortion(LayoutRect flowThreadPortionRect, bool isFirstPortion, bool isLastPortion) const
+LayoutRect RenderRegion::overflowRectForFlowThreadPortion(const LayoutRect& flowThreadPortionRect, bool isFirstPortion, bool isLastPortion) const
 {
     ASSERT(isValid());
 
diff --git a/Source/core/rendering/RenderRegion.h b/Source/core/rendering/RenderRegion.h
index 435dbf3..d06df36 100644
--- a/Source/core/rendering/RenderRegion.h
+++ b/Source/core/rendering/RenderRegion.h
@@ -135,7 +135,7 @@
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
 
-    LayoutRect overflowRectForFlowThreadPortion(LayoutRect flowThreadPortionRect, bool isFirstPortion, bool isLastPortion) const;
+    LayoutRect overflowRectForFlowThreadPortion(const LayoutRect& flowThreadPortionRect, bool isFirstPortion, bool isLastPortion) const;
     void repaintFlowThreadContentRectangle(const LayoutRect& repaintRect, const LayoutRect& flowThreadPortionRect,
         const LayoutRect& flowThreadPortionOverflowRect, const LayoutPoint& regionLocation) const;
 
diff --git a/Source/core/rendering/RenderReplaced.cpp b/Source/core/rendering/RenderReplaced.cpp
index 7798d0b..93db7ed 100644
--- a/Source/core/rendering/RenderReplaced.cpp
+++ b/Source/core/rendering/RenderReplaced.cpp
@@ -105,6 +105,8 @@
 
 void RenderReplaced::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     if (!shouldPaint(paintInfo, paintOffset))
         return;
     
@@ -156,13 +158,13 @@
         if (style()->hasBorderRadius())
             paintInfo.context->restore();
     }
-        
+
     // The selection tint never gets clipped by border-radius rounding, since we want it to run right up to the edges of
     // surrounding content.
     if (drawSelectionTint) {
         LayoutRect selectionPaintingRect = localSelectionRect();
         selectionPaintingRect.moveBy(adjustedPaintOffset);
-        paintInfo.context->fillRect(pixelSnappedIntRect(selectionPaintingRect), selectionBackgroundColor(), style()->colorSpace());
+        paintInfo.context->fillRect(pixelSnappedIntRect(selectionPaintingRect), selectionBackgroundColor());
     }
 }
 
@@ -174,7 +176,7 @@
 
     if (!paintInfo.shouldPaintWithinRoot(this))
         return false;
-        
+
     // if we're invisible or haven't received a layout yet, then just bail.
     if (style()->visibility() != VISIBLE)
         return false;
@@ -190,7 +192,7 @@
         top = min(selTop, top);
         bottom = max(selBottom, bottom);
     }
-    
+
     LayoutRect localRepaintRect = paintInfo.rect;
     localRepaintRect.inflate(maximalOutlineSize(paintInfo.phase));
     if (adjustedPaintOffset.x() + visualOverflowRect().x() >= localRepaintRect.maxX() || adjustedPaintOffset.x() + visualOverflowRect().maxX() <= localRepaintRect.x())
@@ -247,6 +249,13 @@
     return false;
 }
 
+bool RenderReplaced::needsPreferredWidthsRecalculation() const
+{
+    // If the height is a percentage and the width is auto, then the containingBlocks's height changing can cause
+    // this node to change it's preferred width because it maintains aspect ratio.
+    return hasRelativeLogicalHeight() && style()->logicalWidth().isAuto() && !hasAutoHeightOrContainingBlockWithAutoHeight();
+}
+
 static inline bool rendererHasAspectRatio(const RenderObject* renderer)
 {
     ASSERT(renderer);
diff --git a/Source/core/rendering/RenderReplaced.h b/Source/core/rendering/RenderReplaced.h
index 7c1e223..0b9ed07 100644
--- a/Source/core/rendering/RenderReplaced.h
+++ b/Source/core/rendering/RenderReplaced.h
@@ -38,6 +38,8 @@
     bool hasReplacedLogicalWidth() const;
     bool hasReplacedLogicalHeight() const;
 
+    virtual bool needsPreferredWidthsRecalculation() const OVERRIDE;
+
     virtual void reportMemoryUsage(MemoryObjectInfo*) const OVERRIDE FINAL;
 
 protected:
diff --git a/Source/core/rendering/RenderReplica.cpp b/Source/core/rendering/RenderReplica.cpp
index 5f19135..d8cd92b 100644
--- a/Source/core/rendering/RenderReplica.cpp
+++ b/Source/core/rendering/RenderReplica.cpp
@@ -71,6 +71,8 @@
 
 void RenderReplica::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseMask)
         return;
  
diff --git a/Source/core/rendering/RenderScrollbar.cpp b/Source/core/rendering/RenderScrollbar.cpp
index 2732a5f..51acda5 100644
--- a/Source/core/rendering/RenderScrollbar.cpp
+++ b/Source/core/rendering/RenderScrollbar.cpp
@@ -26,7 +26,7 @@
 #include "config.h"
 #include "core/rendering/RenderScrollbar.h"
 
-#include "core/css/resolver/StyleResolver.h"
+#include "core/css/PseudoStyleRequest.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/rendering/RenderPart.h"
diff --git a/Source/core/rendering/RenderScrollbarTheme.cpp b/Source/core/rendering/RenderScrollbarTheme.cpp
index a655fb8..13aca53 100644
--- a/Source/core/rendering/RenderScrollbarTheme.cpp
+++ b/Source/core/rendering/RenderScrollbarTheme.cpp
@@ -84,11 +84,11 @@
 {
     if (!hasButtons(scrollbar))
         return scrollbar->frameRect();
-    
+
     int startLength;
     int endLength;
     buttonSizesAlongTrackAxis(scrollbar, startLength, endLength);
-    
+
     return toRenderScrollbar(scrollbar)->trackRect(startLength, endLength);
 }
 
@@ -110,7 +110,7 @@
 void RenderScrollbarTheme::paintScrollCorner(ScrollView*, GraphicsContext* context, const IntRect& cornerRect)
 {
     // FIXME: Implement.
-    context->fillRect(cornerRect, Color::white, ColorSpaceDeviceRGB);
+    context->fillRect(cornerRect, Color::white);
 }
 
 void RenderScrollbarTheme::paintScrollbarBackground(GraphicsContext* context, ScrollbarThemeClient* scrollbar)
diff --git a/Source/core/rendering/RenderTable.cpp b/Source/core/rendering/RenderTable.cpp
index 10f2f4a..4df5fed 100644
--- a/Source/core/rendering/RenderTable.cpp
+++ b/Source/core/rendering/RenderTable.cpp
@@ -621,6 +621,8 @@
 
 void RenderTable::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     LayoutPoint adjustedPaintOffset = paintOffset + location();
 
     PaintPhase paintPhase = paintInfo.phase;
diff --git a/Source/core/rendering/RenderTableRow.cpp b/Source/core/rendering/RenderTableRow.cpp
index db2f8cd..bbad6c4 100644
--- a/Source/core/rendering/RenderTableRow.cpp
+++ b/Source/core/rendering/RenderTableRow.cpp
@@ -244,6 +244,7 @@
 void RenderTableRow::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     ASSERT(hasSelfPaintingLayer());
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
 
     paintOutlineForRowIfNeeded(paintInfo, paintOffset);
     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
diff --git a/Source/core/rendering/RenderTableSection.cpp b/Source/core/rendering/RenderTableSection.cpp
index 921dc03..025fb7e 100644
--- a/Source/core/rendering/RenderTableSection.cpp
+++ b/Source/core/rendering/RenderTableSection.cpp
@@ -905,6 +905,8 @@
 
 void RenderTableSection::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     // put this back in when all layout tests can handle it
     // ASSERT(!needsLayout());
     // avoid crashing on bugs that cause us to paint with dirty layout
@@ -1153,9 +1155,8 @@
                             continue;
 
                         if (current.cells[i]->rowSpan() > 1 || current.cells[i]->colSpan() > 1) {
-                            if (spanningCells.contains(current.cells[i]))
+                            if (!spanningCells.add(current.cells[i]).isNewEntry)
                                 continue;
-                            spanningCells.add(current.cells[i]);
                         }
 
                         cells.append(current.cells[i]);
diff --git a/Source/core/rendering/RenderText.cpp b/Source/core/rendering/RenderText.cpp
index 24ecdbf..5c2ff91 100644
--- a/Source/core/rendering/RenderText.cpp
+++ b/Source/core/rendering/RenderText.cpp
@@ -98,7 +98,7 @@
         return;
 
     unsigned length = string->length();
-    const UChar* characters = string->characters();
+    const StringImpl& input = *string->impl();
 
     if (length >= numeric_limits<unsigned>::max())
         CRASH();
@@ -107,28 +107,29 @@
     stringWithPrevious[0] = previous == noBreakSpace ? ' ' : previous;
     for (unsigned i = 1; i < length + 1; i++) {
         // Replace &nbsp with a real space since ICU no longer treats &nbsp as a word separator.
-        if (characters[i - 1] == noBreakSpace)
+        if (input[i - 1] == noBreakSpace)
             stringWithPrevious[i] = ' ';
         else
-            stringWithPrevious[i] = characters[i - 1];
+            stringWithPrevious[i] = input[i - 1];
     }
 
     TextBreakIterator* boundary = wordBreakIterator(stringWithPrevious.characters(), length + 1);
     if (!boundary)
         return;
 
-    StringBuffer<UChar> data(length);
+    StringBuilder result;
+    result.reserveCapacity(length);
 
     int32_t endOfWord;
     int32_t startOfWord = textBreakFirst(boundary);
     for (endOfWord = textBreakNext(boundary); endOfWord != TextBreakDone; startOfWord = endOfWord, endOfWord = textBreakNext(boundary)) {
         if (startOfWord) // Ignore first char of previous string
-            data[startOfWord - 1] = characters[startOfWord - 1] == noBreakSpace ? noBreakSpace : toTitleCase(stringWithPrevious[startOfWord]);
+            result.append(input[startOfWord - 1] == noBreakSpace ? noBreakSpace : toTitleCase(stringWithPrevious[startOfWord]));
         for (int i = startOfWord + 1; i < endOfWord; i++)
-            data[i - 1] = characters[i - 1];
+            result.append(input[i - 1]);
     }
 
-    *string = String::adopt(data);
+    *string = result.toString();
 }
 
 RenderText::RenderText(Node* node, PassRefPtr<StringImpl> str)
@@ -1172,7 +1173,7 @@
     setPreferredLogicalWidthsDirty(false);
 }
 
-bool RenderText::isAllCollapsibleWhitespace()
+bool RenderText::isAllCollapsibleWhitespace() const
 {
     unsigned length = textLength();
     if (is8Bit()) {
@@ -1715,8 +1716,11 @@
 
 int RenderText::previousOffset(int current) const
 {
-    StringImpl* si = m_text.impl();
-    TextBreakIterator* iterator = cursorMovementIterator(si->characters(), si->length());
+    if (isAllASCII() || m_text.is8Bit())
+        return current - 1;
+
+    StringImpl* textImpl = m_text.impl();
+    TextBreakIterator* iterator = cursorMovementIterator(textImpl->characters16(), textImpl->length());
     if (!iterator)
         return current - 1;
 
@@ -1868,8 +1872,11 @@
 
 int RenderText::nextOffset(int current) const
 {
-    StringImpl* si = m_text.impl();
-    TextBreakIterator* iterator = cursorMovementIterator(si->characters(), si->length());
+    if (isAllASCII() || m_text.is8Bit())
+        return current + 1;
+
+    StringImpl* textImpl = m_text.impl();
+    TextBreakIterator* iterator = cursorMovementIterator(textImpl->characters16(), textImpl->length());
     if (!iterator)
         return current + 1;
 
@@ -1877,7 +1884,6 @@
     if (result == TextBreakDone)
         result = current + 1;
 
-
     return result;
 }
 
diff --git a/Source/core/rendering/RenderText.h b/Source/core/rendering/RenderText.h
index 352deac..7dd5a83 100644
--- a/Source/core/rendering/RenderText.h
+++ b/Source/core/rendering/RenderText.h
@@ -134,7 +134,7 @@
 
     void checkConsistency() const;
 
-    bool isAllCollapsibleWhitespace();
+    bool isAllCollapsibleWhitespace() const;
 
     bool canUseSimpleFontCodePath() const { return m_canUseSimpleFontCodePath; }
     bool knownToHaveNoOverflowAndNoFallbackFonts() const { return m_knownToHaveNoOverflowAndNoFallbackFonts; }
diff --git a/Source/core/rendering/RenderTextTrackCue.cpp b/Source/core/rendering/RenderTextTrackCue.cpp
index b1f41cc..694beeb 100644
--- a/Source/core/rendering/RenderTextTrackCue.cpp
+++ b/Source/core/rendering/RenderTextTrackCue.cpp
@@ -43,6 +43,15 @@
     StackStats::LayoutCheckPoint layoutCheckPoint;
     RenderBlock::layout();
 
+#if ENABLE(WEBVTT_REGIONS)
+    // If WebVTT Regions are used, the regular WebVTT layout algorithm is no
+    // longer necessary, since cues having the region parameter set do not have
+    // any positioning parameters. Also, in this case, the regions themselves
+    // have positioning information.
+    if (!m_cue->regionId().isEmpty())
+        return;
+#endif
+
     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
 
     if (m_cue->cueType()== TextTrackCue::WebVTT) {
diff --git a/Source/core/rendering/RenderTheme.cpp b/Source/core/rendering/RenderTheme.cpp
index ea5d338..7b73859 100644
--- a/Source/core/rendering/RenderTheme.cpp
+++ b/Source/core/rendering/RenderTheme.cpp
@@ -53,9 +53,9 @@
 #include "core/rendering/RenderMeter.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <public/Platform.h>
-#include <public/WebFallbackThemeEngine.h>
-#include <public/WebRect.h>
+#include "public/platform/Platform.h"
+#include "public/platform/WebFallbackThemeEngine.h"
+#include "public/platform/WebRect.h"
 
 #if ENABLE(INPUT_SPEECH)
 #include "core/rendering/RenderInputSpeech.h"
@@ -92,7 +92,7 @@
 {
 }
 
-void RenderTheme::adjustStyle(StyleResolver* styleResolver, RenderStyle* style, Element* e, bool UAHasAppearance, const BorderData& border, const FillLayer& background, const Color& backgroundColor)
+void RenderTheme::adjustStyle(RenderStyle* style, Element* e, bool UAHasAppearance, const BorderData& border, const FillLayer& background, const Color& backgroundColor)
 {
     // Force inline and table display styles to be inline-block (except for table- which is block)
     ControlPart part = style->appearance();
@@ -116,7 +116,7 @@
         return;
 
     if (shouldUseFallbackTheme(style)) {
-        adjustStyleUsingFallbackTheme(styleResolver, style, e);
+        adjustStyleUsingFallbackTheme(style, e);
         return;
     }
 
@@ -203,24 +203,24 @@
     switch (style->appearance()) {
 #if !USE(NEW_THEME)
     case CheckboxPart:
-        return adjustCheckboxStyle(styleResolver, style, e);
+        return adjustCheckboxStyle(style, e);
     case RadioPart:
-        return adjustRadioStyle(styleResolver, style, e);
+        return adjustRadioStyle(style, e);
     case PushButtonPart:
     case SquareButtonPart:
     case ButtonPart:
-        return adjustButtonStyle(styleResolver, style, e);
+        return adjustButtonStyle(style, e);
     case InnerSpinButtonPart:
-        return adjustInnerSpinButtonStyle(styleResolver, style, e);
+        return adjustInnerSpinButtonStyle(style, e);
 #endif
     case TextFieldPart:
-        return adjustTextFieldStyle(styleResolver, style, e);
+        return adjustTextFieldStyle(style, e);
     case TextAreaPart:
-        return adjustTextAreaStyle(styleResolver, style, e);
+        return adjustTextAreaStyle(style, e);
     case MenulistPart:
-        return adjustMenuListStyle(styleResolver, style, e);
+        return adjustMenuListStyle(style, e);
     case MenulistButtonPart:
-        return adjustMenuListButtonStyle(styleResolver, style, e);
+        return adjustMenuListButtonStyle(style, e);
     case MediaPlayButtonPart:
     case MediaCurrentTimePart:
     case MediaTimeRemainingPart:
@@ -228,35 +228,35 @@
     case MediaExitFullscreenButtonPart:
     case MediaMuteButtonPart:
     case MediaVolumeSliderContainerPart:
-        return adjustMediaControlStyle(styleResolver, style, e);
+        return adjustMediaControlStyle(style, e);
     case MediaSliderPart:
     case MediaVolumeSliderPart:
     case MediaFullScreenVolumeSliderPart:
     case SliderHorizontalPart:
     case SliderVerticalPart:
-        return adjustSliderTrackStyle(styleResolver, style, e);
+        return adjustSliderTrackStyle(style, e);
     case SliderThumbHorizontalPart:
     case SliderThumbVerticalPart:
-        return adjustSliderThumbStyle(styleResolver, style, e);
+        return adjustSliderThumbStyle(style, e);
     case SearchFieldPart:
-        return adjustSearchFieldStyle(styleResolver, style, e);
+        return adjustSearchFieldStyle(style, e);
     case SearchFieldCancelButtonPart:
-        return adjustSearchFieldCancelButtonStyle(styleResolver, style, e);
+        return adjustSearchFieldCancelButtonStyle(style, e);
     case SearchFieldDecorationPart:
-        return adjustSearchFieldDecorationStyle(styleResolver, style, e);
+        return adjustSearchFieldDecorationStyle(style, e);
     case SearchFieldResultsDecorationPart:
-        return adjustSearchFieldResultsDecorationStyle(styleResolver, style, e);
+        return adjustSearchFieldResultsDecorationStyle(style, e);
     case ProgressBarPart:
-        return adjustProgressBarStyle(styleResolver, style, e);
+        return adjustProgressBarStyle(style, e);
     case MeterPart:
     case RelevancyLevelIndicatorPart:
     case ContinuousCapacityLevelIndicatorPart:
     case DiscreteCapacityLevelIndicatorPart:
     case RatingLevelIndicatorPart:
-        return adjustMeterStyle(styleResolver, style, e);
+        return adjustMeterStyle(style, e);
 #if ENABLE(INPUT_SPEECH)
     case InputSpeechButtonPart:
-        return adjustInputFieldSpeechButtonStyle(styleResolver, style, e);
+        return adjustInputFieldSpeechButtonStyle(style, e);
 #endif
     default:
         break;
@@ -485,11 +485,12 @@
 
     if (RuntimeEnabledFeatures::dataListElementEnabled()) {
         runtimeCSS.appendLiteral("datalist {display: none ;}");
-#if ENABLE(INPUT_TYPE_COLOR)
-        runtimeCSS.appendLiteral("input[type=\"color\"][list] { -webkit-appearance: menulist; width: 88px; height: 23px;}");
-        runtimeCSS.appendLiteral("input[type=\"color\"][list]::-webkit-color-swatch-wrapper { padding-left: 8px; padding-right: 24px;}");
-        runtimeCSS.appendLiteral("input[type=\"color\"][list]::-webkit-color-swatch { border-color: #000000;}");
-#endif
+
+        if (RuntimeEnabledFeatures::inputTypeColorEnabled()) {
+            runtimeCSS.appendLiteral("input[type=\"color\"][list] { -webkit-appearance: menulist; width: 88px; height: 23px;}");
+            runtimeCSS.appendLiteral("input[type=\"color\"][list]::-webkit-color-swatch-wrapper { padding-left: 8px; padding-right: 24px;}");
+            runtimeCSS.appendLiteral("input[type=\"color\"][list]::-webkit-color-swatch { border-color: #000000;}");
+        }
     }
     if (RuntimeEnabledFeatures::dialogElementEnabled()) {
         runtimeCSS.appendLiteral("dialog:not([open]) { display: none; }");
@@ -646,9 +647,16 @@
 
 static bool isBackgroundOrBorderStyled(const RenderStyle& style, const BorderData& border, const FillLayer& background, const Color& backgroundColor)
 {
+    // Code below excludes the background-repeat from comparison by resetting it
+    FillLayer backgroundCopy = background;
+    FillLayer backgroundLayersCopy = *style.backgroundLayers();
+    backgroundCopy.setRepeatX(NoRepeatFill);
+    backgroundCopy.setRepeatY(NoRepeatFill);
+    backgroundLayersCopy.setRepeatX(NoRepeatFill);
+    backgroundLayersCopy.setRepeatY(NoRepeatFill);
     // Test the style to see if the UA border and background match.
     return style.border() != border
-        || *style.backgroundLayers() != background
+        || backgroundLayersCopy != backgroundCopy
         || style.visitedDependentColor(CSSPropertyBackgroundColor) != backgroundColor;
 }
 
@@ -848,7 +856,7 @@
 
 #if !USE(NEW_THEME)
 
-void RenderTheme::adjustCheckboxStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderTheme::adjustCheckboxStyle(RenderStyle* style, Element*) const
 {
     // A summary of the rules for checkbox designed to match WinIE:
     // width/height - honored (WinIE actually scales its control for small widths, but lets it overflow for small heights.)
@@ -863,7 +871,7 @@
     style->resetBorder();
 }
 
-void RenderTheme::adjustRadioStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderTheme::adjustRadioStyle(RenderStyle* style, Element*) const
 {
     // A summary of the rules for checkbox designed to match WinIE:
     // width/height - honored (WinIE actually scales its control for small widths, but lets it overflow for small heights.)
@@ -878,7 +886,7 @@
     style->resetBorder();
 }
 
-void RenderTheme::adjustButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderTheme::adjustButtonStyle(RenderStyle* style, Element*) const
 {
     // Most platforms will completely honor all CSS, and so we have no need to
     // adjust the style at all by default. We will still allow the theme a crack
@@ -886,27 +894,27 @@
     setButtonSize(style);
 }
 
-void RenderTheme::adjustInnerSpinButtonStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustInnerSpinButtonStyle(RenderStyle*, Element*) const
 {
 }
 #endif
 
-void RenderTheme::adjustTextFieldStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustTextFieldStyle(RenderStyle*, Element*) const
 {
 }
 
-void RenderTheme::adjustTextAreaStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustTextAreaStyle(RenderStyle*, Element*) const
 {
 }
 
-void RenderTheme::adjustMenuListStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustMenuListStyle(RenderStyle*, Element*) const
 {
 }
 
 #if ENABLE(INPUT_SPEECH)
-void RenderTheme::adjustInputFieldSpeechButtonStyle(StyleResolver* styleResolver, RenderStyle* style, Element* element) const
+void RenderTheme::adjustInputFieldSpeechButtonStyle(RenderStyle* style, Element* element) const
 {
-    RenderInputSpeech::adjustInputFieldSpeechButtonStyle(styleResolver, style, element);
+    RenderInputSpeech::adjustInputFieldSpeechButtonStyle(style, element);
 }
 
 bool RenderTheme::paintInputFieldSpeechButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
@@ -915,7 +923,7 @@
 }
 #endif
 
-void RenderTheme::adjustMeterStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderTheme::adjustMeterStyle(RenderStyle* style, Element*) const
 {
 }
 
@@ -1002,7 +1010,7 @@
     }
     RefPtr<HTMLCollection> options = dataList->options();
     GraphicsContextStateSaver stateSaver(*paintInfo.context);
-    paintInfo.context->setFillColor(o->style()->visitedDependentColor(CSSPropertyColor), ColorSpaceDeviceRGB);
+    paintInfo.context->setFillColor(o->style()->visitedDependentColor(CSSPropertyColor));
     for (unsigned i = 0; Node* node = options->item(i); i++) {
         ASSERT(node->hasTagName(optionTag));
         HTMLOptionElement* optionElement = toHTMLOptionElement(node);
@@ -1031,7 +1039,7 @@
     return 0;
 }
 
-void RenderTheme::adjustProgressBarStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustProgressBarStyle(RenderStyle*, Element*) const
 {
 }
 
@@ -1040,19 +1048,19 @@
     return inputElement->isSteppable() && !inputElement->isRangeControl();
 }
 
-void RenderTheme::adjustMenuListButtonStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustMenuListButtonStyle(RenderStyle*, Element*) const
 {
 }
 
-void RenderTheme::adjustMediaControlStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustMediaControlStyle(RenderStyle*, Element*) const
 {
 }
 
-void RenderTheme::adjustSliderTrackStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustSliderTrackStyle(RenderStyle*, Element*) const
 {
 }
 
-void RenderTheme::adjustSliderThumbStyle(StyleResolver*, RenderStyle* style, Element* element) const
+void RenderTheme::adjustSliderThumbStyle(RenderStyle* style, Element* element) const
 {
     adjustSliderThumbSize(style, element);
 }
@@ -1061,19 +1069,19 @@
 {
 }
 
-void RenderTheme::adjustSearchFieldStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustSearchFieldStyle(RenderStyle*, Element*) const
 {
 }
 
-void RenderTheme::adjustSearchFieldCancelButtonStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustSearchFieldCancelButtonStyle(RenderStyle*, Element*) const
 {
 }
 
-void RenderTheme::adjustSearchFieldDecorationStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustSearchFieldDecorationStyle(RenderStyle*, Element*) const
 {
 }
 
-void RenderTheme::adjustSearchFieldResultsDecorationStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderTheme::adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const
 {
 }
 
@@ -1092,7 +1100,7 @@
     Page::scheduleForcedStyleRecalcForAllPages();
 }
 
-Color RenderTheme::systemColor(int cssValueId) const
+Color RenderTheme::systemColor(CSSValueID cssValueId) const
 {
     switch (cssValueId) {
     case CSSValueActiveborder:
@@ -1153,6 +1161,20 @@
         return 0xFFCCCCCC;
     case CSSValueWindowtext:
         return 0xFF000000;
+    case CSSValueInternalActiveListBoxSelection:
+        return activeListBoxSelectionBackgroundColor();
+        break;
+    case CSSValueInternalActiveListBoxSelectionText:
+        return activeListBoxSelectionForegroundColor();
+        break;
+    case CSSValueInternalInactiveListBoxSelection:
+        return inactiveListBoxSelectionBackgroundColor();
+        break;
+    case CSSValueInternalInactiveListBoxSelectionText:
+        return inactiveListBoxSelectionForegroundColor();
+        break;
+    default:
+        break;
     }
     return Color();
 }
@@ -1238,9 +1260,7 @@
 {
     return type == InputTypeNames::text() || type == InputTypeNames::search() || type == InputTypeNames::url()
         || type == InputTypeNames::telephone() || type == InputTypeNames::email() || type == InputTypeNames::number()
-#if ENABLE(INPUT_TYPE_COLOR)
         || type == InputTypeNames::color()
-#endif
         || type == InputTypeNames::date()
         || type == InputTypeNames::datetime()
         || type == InputTypeNames::datetimelocal()
@@ -1266,14 +1286,14 @@
     return false;
 }
 
-void RenderTheme::adjustStyleUsingFallbackTheme(StyleResolver* styleResolver, RenderStyle* style, Element* e)
+void RenderTheme::adjustStyleUsingFallbackTheme(RenderStyle* style, Element* e)
 {
     ControlPart part = style->appearance();
     switch (part) {
     case CheckboxPart:
-        return adjustCheckboxStyleUsingFallbackTheme(styleResolver, style, e);
+        return adjustCheckboxStyleUsingFallbackTheme(style, e);
     case RadioPart:
-        return adjustRadioStyleUsingFallbackTheme(styleResolver, style, e);
+        return adjustRadioStyleUsingFallbackTheme(style, e);
     default:
         break;
     }
@@ -1324,7 +1344,7 @@
     return false;
 }
 
-void RenderTheme::adjustCheckboxStyleUsingFallbackTheme(StyleResolver*, RenderStyle* style, Element*) const
+void RenderTheme::adjustCheckboxStyleUsingFallbackTheme(RenderStyle* style, Element*) const
 {
     // If the width and height are both specified, then we have nothing to do.
     if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
@@ -1366,7 +1386,7 @@
     return false;
 }
 
-void RenderTheme::adjustRadioStyleUsingFallbackTheme(StyleResolver*, RenderStyle* style, Element*) const
+void RenderTheme::adjustRadioStyleUsingFallbackTheme(RenderStyle* style, Element*) const
 {
     // If the width and height are both specified, then we have nothing to do.
     if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
diff --git a/Source/core/rendering/RenderTheme.h b/Source/core/rendering/RenderTheme.h
index d95d308..cbf539b 100644
--- a/Source/core/rendering/RenderTheme.h
+++ b/Source/core/rendering/RenderTheme.h
@@ -69,7 +69,7 @@
     // metrics and defaults given the contents of the style.  This includes sophisticated operations like
     // selection of control size based off the font, the disabling of appearance when certain other properties like
     // "border" are set, or if the appearance is not supported by the theme.
-    void adjustStyle(StyleResolver*, RenderStyle*, Element*,  bool UAHasAppearance,
+    void adjustStyle(RenderStyle*, Element*,  bool UAHasAppearance,
                      const BorderData&, const FillLayer&, const Color& backgroundColor);
 
     // This method is called to paint the widget as a background of the RenderObject.  A widget's foreground, e.g., the
@@ -161,8 +161,8 @@
     virtual double caretBlinkInterval() const { return 0.5; }
 
     // System fonts and colors for CSS.
-    virtual void systemFont(int cssValueId, FontDescription&) const = 0;
-    virtual Color systemColor(int cssValueId) const;
+    virtual void systemFont(CSSValueID, FontDescription&) const = 0;
+    virtual Color systemColor(CSSValueID) const;
 
     virtual int minimumMenuListSize(RenderStyle*) const { return 0; }
 
@@ -237,64 +237,64 @@
 
 #if !USE(NEW_THEME)
     // Methods for each appearance value.
-    virtual void adjustCheckboxStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustCheckboxStyle(RenderStyle*, Element*) const;
     virtual bool paintCheckbox(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual void setCheckboxSize(RenderStyle*) const { }
 
-    virtual void adjustRadioStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustRadioStyle(RenderStyle*, Element*) const;
     virtual bool paintRadio(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual void setRadioSize(RenderStyle*) const { }
 
-    virtual void adjustButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual void setButtonSize(RenderStyle*) const { }
 
-    virtual void adjustInnerSpinButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintInnerSpinButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 #endif
 
-    virtual void adjustTextFieldStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustTextFieldStyle(RenderStyle*, Element*) const;
     virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustTextAreaStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustTextAreaStyle(RenderStyle*, Element*) const;
     virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustMenuListStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustMenuListStyle(RenderStyle*, Element*) const;
     virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustMenuListButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustMeterStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustMeterStyle(RenderStyle*, Element*) const;
     virtual bool paintMeter(RenderObject*, const PaintInfo&, const IntRect&);
 
-    virtual void adjustProgressBarStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustProgressBarStyle(RenderStyle*, Element*) const;
     virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
 #if ENABLE(INPUT_SPEECH)
-    virtual void adjustInputFieldSpeechButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustInputFieldSpeechButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintInputFieldSpeechButton(RenderObject*, const PaintInfo&, const IntRect&);
 #endif
 
-    virtual void adjustSliderTrackStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSliderTrackStyle(RenderStyle*, Element*) const;
     virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustSliderThumbStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSliderThumbStyle(RenderStyle*, Element*) const;
     virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustSearchFieldStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchField(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustSearchFieldCancelButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldCancelButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchFieldCancelButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustSearchFieldDecorationStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldDecorationStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchFieldDecoration(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustSearchFieldResultsDecorationStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustMediaControlStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustMediaControlStyle(RenderStyle*, Element*) const;
     virtual bool paintMediaFullscreenButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaPlayButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaOverlayPlayButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
@@ -316,11 +316,11 @@
     virtual bool paintMediaFullScreenVolumeSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
     virtual bool shouldUseFallbackTheme(RenderStyle*) const;
-    void adjustStyleUsingFallbackTheme(StyleResolver*, RenderStyle*, Element*);
+    void adjustStyleUsingFallbackTheme(RenderStyle*, Element*);
     bool paintUsingFallbackTheme(RenderObject*, const PaintInfo&, const IntRect&);
-    void adjustCheckboxStyleUsingFallbackTheme(StyleResolver*, RenderStyle*, Element*) const;
+    void adjustCheckboxStyleUsingFallbackTheme(RenderStyle*, Element*) const;
     bool paintCheckboxUsingFallbackTheme(RenderObject*, const PaintInfo&, const IntRect&);
-    void adjustRadioStyleUsingFallbackTheme(StyleResolver*, RenderStyle*, Element*) const;
+    void adjustRadioStyleUsingFallbackTheme(RenderStyle*, Element*) const;
     bool paintRadioUsingFallbackTheme(RenderObject*, const PaintInfo&, const IntRect&);
 
 public:
diff --git a/Source/core/rendering/RenderThemeChromiumAndroid.cpp b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
index 3eae660..40a7cbe 100644
--- a/Source/core/rendering/RenderThemeChromiumAndroid.cpp
+++ b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
@@ -37,8 +37,8 @@
 #include "core/rendering/RenderProgress.h"
 #include "core/rendering/RenderSlider.h"
 
-#include <public/android/WebThemeEngine.h>
-#include <public/Platform.h>
+#include "public/platform/android/WebThemeEngine.h"
+#include "public/platform/Platform.h"
 
 namespace WebCore {
 
@@ -57,7 +57,7 @@
 {
 }
 
-Color RenderThemeChromiumAndroid::systemColor(int cssValueId) const
+Color RenderThemeChromiumAndroid::systemColor(CSSValueID cssValueId) const
 {
     if (isRunningLayoutTest() && cssValueId == CSSValueButtonface) {
         // Match Chromium Linux' button color in layout tests.
@@ -78,7 +78,7 @@
         String(themeChromiumAndroidUserAgentStyleSheet, sizeof(themeChromiumAndroidUserAgentStyleSheet));
 }
 
-void RenderThemeChromiumAndroid::adjustInnerSpinButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumAndroid::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const
 {
     if (isRunningLayoutTest()) {
         // Match Chromium Linux spin button style in layout tests.
diff --git a/Source/core/rendering/RenderThemeChromiumAndroid.h b/Source/core/rendering/RenderThemeChromiumAndroid.h
index 0d280f4..7de033d 100644
--- a/Source/core/rendering/RenderThemeChromiumAndroid.h
+++ b/Source/core/rendering/RenderThemeChromiumAndroid.h
@@ -35,9 +35,9 @@
     static PassRefPtr<RenderTheme> create();
     virtual String extraDefaultStyleSheet() OVERRIDE;
 
-    virtual Color systemColor(int cssValidId) const OVERRIDE;
+    virtual Color systemColor(CSSValueID) const OVERRIDE;
 
-    virtual void adjustInnerSpinButtonStyle(StyleResolver*, RenderStyle*, Element*) const OVERRIDE;
+    virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const OVERRIDE;
 
     virtual bool delegatesMenuListRendering() const OVERRIDE { return true; }
 
diff --git a/Source/core/rendering/RenderThemeChromiumDefault.cpp b/Source/core/rendering/RenderThemeChromiumDefault.cpp
index 33a78f8..7aab69b 100644
--- a/Source/core/rendering/RenderThemeChromiumDefault.cpp
+++ b/Source/core/rendering/RenderThemeChromiumDefault.cpp
@@ -33,9 +33,9 @@
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderProgress.h"
-#include <public/default/WebThemeEngine.h>
-#include <public/Platform.h>
-#include <public/WebRect.h>
+#include "public/platform/default/WebThemeEngine.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebRect.h"
 
 namespace WebCore {
 
@@ -87,7 +87,7 @@
 {
 }
 
-Color RenderThemeChromiumDefault::systemColor(int cssValueId) const
+Color RenderThemeChromiumDefault::systemColor(CSSValueID cssValueId) const
 {
     static const Color defaultButtonGrayColor(0xffdddddd);
     static const Color defaultMenuColor(0xfff7f7f7);
@@ -375,7 +375,7 @@
     return false;
 }
 
-void RenderThemeChromiumDefault::adjustInnerSpinButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumDefault::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const
 {
     IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartInnerSpinButton);
 
diff --git a/Source/core/rendering/RenderThemeChromiumDefault.h b/Source/core/rendering/RenderThemeChromiumDefault.h
index f22410d..25423ed 100644
--- a/Source/core/rendering/RenderThemeChromiumDefault.h
+++ b/Source/core/rendering/RenderThemeChromiumDefault.h
@@ -38,7 +38,7 @@
     static PassRefPtr<RenderTheme> create();
     virtual String extraDefaultStyleSheet();
 
-    virtual Color systemColor(int cssValidId) const;
+    virtual Color systemColor(CSSValueID) const;
 
     // A method asking if the control changes its tint when the window has focus or not.
     virtual bool controlSupportsTints(const RenderObject*) const;
@@ -73,7 +73,7 @@
     virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
     virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
 
-    virtual void adjustInnerSpinButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintInnerSpinButton(RenderObject*, const PaintInfo&, const IntRect&);
 
     virtual bool popsMenuBySpaceOrReturn() const OVERRIDE { return true; }
diff --git a/Source/core/rendering/RenderThemeChromiumFontProvider.h b/Source/core/rendering/RenderThemeChromiumFontProvider.h
index 0f7eeac..57589c2 100644
--- a/Source/core/rendering/RenderThemeChromiumFontProvider.h
+++ b/Source/core/rendering/RenderThemeChromiumFontProvider.h
@@ -26,6 +26,8 @@
 #ifndef RenderThemeChromiumFontProvider_h
 #define RenderThemeChromiumFontProvider_h
 
+#include "CSSValueKeywords.h"
+
 namespace WTF {
 class String;
 }
@@ -36,7 +38,7 @@
 
 class RenderThemeChromiumFontProvider {
 public:
-    static void systemFont(int propId, FontDescription&);
+    static void systemFont(CSSValueID, FontDescription&);
     static void setDefaultFontSize(int);
 
 protected:
diff --git a/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp b/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
index d84505c..c09bbcd 100644
--- a/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
+++ b/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
@@ -41,11 +41,11 @@
 }
 
 // static
-void RenderThemeChromiumFontProvider::systemFont(int propId, FontDescription& fontDescription)
+void RenderThemeChromiumFontProvider::systemFont(CSSValueID valueID, FontDescription& fontDescription)
 {
     float fontSize = s_defaultFontSize;
 
-    switch (propId) {
+    switch (valueID) {
     case CSSValueWebkitMiniControl:
     case CSSValueWebkitSmallControl:
     case CSSValueWebkitControl:
@@ -56,6 +56,8 @@
         static const float pixelsPerInch = 96.0f;
         fontSize -= (2.0f / pointsPerInch) * pixelsPerInch;
         break;
+    default:
+        break;
     }
 
     fontDescription.firstFamily().setFamily(defaultGUIFont());
diff --git a/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp b/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp
index 9d4dbcc..a4225c2 100644
--- a/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp
+++ b/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp
@@ -119,13 +119,13 @@
 }
 
 // static
-void RenderThemeChromiumFontProvider::systemFont(int propId, FontDescription& fontDescription)
+void RenderThemeChromiumFontProvider::systemFont(CSSValueID valueID, FontDescription& fontDescription)
 {
     // This logic owes much to RenderThemeSafari.cpp.
     FontDescription* cachedDesc = 0;
     AtomicString faceName;
     float fontSize = 0;
-    switch (propId) {
+    switch (valueID) {
     case CSSValueSmallCaption:
         cachedDesc = &smallSystemFont();
         if (!smallSystemFont().isAbsoluteSize()) {
diff --git a/Source/core/rendering/RenderThemeChromiumMac.h b/Source/core/rendering/RenderThemeChromiumMac.h
index 0c950fa..aea6af1 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.h
+++ b/Source/core/rendering/RenderThemeChromiumMac.h
@@ -59,7 +59,7 @@
     virtual void platformColorsDidChange();
 
     // System fonts.
-    virtual void systemFont(int cssValueId, FontDescription&) const;
+    virtual void systemFont(CSSValueID, FontDescription&) const;
 
     virtual int minimumMenuListSize(RenderStyle*) const;
 
@@ -86,7 +86,7 @@
     // Returns the duration of the animation for the progress bar.
     virtual double animationDurationForProgressBar(RenderProgress*) const;
 
-    virtual Color systemColor(int cssValueId) const;
+    virtual Color systemColor(CSSValueID) const;
 
 protected:
     RenderThemeChromiumMac();
@@ -95,18 +95,18 @@
     virtual bool supportsSelectionForegroundColors() const { return false; }
 
     virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustTextFieldStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustTextFieldStyle(RenderStyle*, Element*) const;
 
     virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustTextAreaStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustTextAreaStyle(RenderStyle*, Element*) const;
 
     virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustMenuListStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustMenuListStyle(RenderStyle*, Element*) const;
 
     virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustMenuListButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const;
 
-    virtual void adjustProgressBarStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustProgressBarStyle(RenderStyle*, Element*) const;
     virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&);
 
     virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
@@ -114,15 +114,15 @@
     virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
 
     virtual bool paintSearchField(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustSearchFieldStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldStyle(RenderStyle*, Element*) const;
 
-    virtual void adjustSearchFieldCancelButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldCancelButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchFieldCancelButton(RenderObject*, const PaintInfo&, const IntRect&);
 
-    virtual void adjustSearchFieldDecorationStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldDecorationStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchFieldDecoration(RenderObject*, const PaintInfo&, const IntRect&);
 
-    virtual void adjustSearchFieldResultsDecorationStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&);
 
     virtual bool supportsClosedCaptioning() const { return true; }
@@ -141,7 +141,7 @@
     void setSizeFromFont(RenderStyle*, const IntSize* sizes) const;
     IntSize sizeForFont(RenderStyle*, const IntSize* sizes) const;
     IntSize sizeForSystemFont(RenderStyle*, const IntSize* sizes) const;
-    void setFontFromControlSize(StyleResolver*, RenderStyle*, NSControlSize) const;
+    void setFontFromControlSize(RenderStyle*, NSControlSize) const;
 
     void updateCheckedState(NSCell*, const RenderObject*);
     void updateEnabledState(NSCell*, const RenderObject*);
diff --git a/Source/core/rendering/RenderThemeChromiumMac.mm b/Source/core/rendering/RenderThemeChromiumMac.mm
index e7c1533..d199579 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.mm
+++ b/Source/core/rendering/RenderThemeChromiumMac.mm
@@ -25,7 +25,6 @@
 #import "HTMLNames.h"
 #import "UserAgentStyleSheets.h"
 #import "core/css/CSSValueList.h"
-#import "core/css/resolver/StyleResolver.h"
 #import "core/dom/Document.h"
 #import "core/dom/Element.h"
 #import "core/fileapi/FileList.h"
@@ -253,7 +252,7 @@
     return fontWeights[appKitFontWeight - 1];
 }
 
-void RenderThemeChromiumMac::systemFont(int cssValueId, FontDescription& fontDescription) const
+void RenderThemeChromiumMac::systemFont(CSSValueID cssValueId, FontDescription& fontDescription) const
 {
     DEFINE_STATIC_LOCAL(FontDescription, systemFont, ());
     DEFINE_STATIC_LOCAL(FontDescription, smallSystemFont, ());
@@ -388,7 +387,7 @@
     RenderTheme::platformColorsDidChange();
 }
 
-Color RenderThemeChromiumMac::systemColor(int cssValueId) const
+Color RenderThemeChromiumMac::systemColor(CSSValueID cssValueId) const
 {
     {
         HashMap<int, RGBA32>::iterator it = m_systemColorCache.find(cssValueId);
@@ -493,6 +492,8 @@
         case CSSValueWindowtext:
             color = convertNSColorToColor([NSColor windowFrameTextColor]);
             break;
+        default:
+            break;
     }
 
     if (!color.isValid())
@@ -660,6 +661,19 @@
     return NSMiniControlSize;
 }
 
+// We don't use controlSizeForFont() for cancel buttons because it needs to fit
+// into the search field. The font size will already be modified by
+// setFontFromControlSize() called on the search field.
+static NSControlSize cancelButtonControlSizeForFont(RenderStyle* style)
+{
+    int fontSize = style->fontSize();
+    if (fontSize >= 13)
+        return NSRegularControlSize;
+    if (fontSize >= 11)
+        return NSSmallControlSize;
+    return NSMiniControlSize;
+}
+
 void RenderThemeChromiumMac::setControlSize(NSCell* cell, const IntSize* sizes, const IntSize& minSize, float zoomLevel)
 {
     NSControlSize size;
@@ -703,7 +717,7 @@
         style->setHeight(Length(size.height(), Fixed));
 }
 
-void RenderThemeChromiumMac::setFontFromControlSize(StyleResolver*, RenderStyle* style, NSControlSize controlSize) const
+void RenderThemeChromiumMac::setFontFromControlSize(RenderStyle* style, NSControlSize controlSize) const
 {
     FontDescription fontDescription;
     fontDescription.setIsAbsoluteSize(true);
@@ -762,7 +776,7 @@
     return false;
 }
 
-void RenderThemeChromiumMac::adjustTextFieldStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderThemeChromiumMac::adjustTextFieldStyle(RenderStyle*, Element*) const
 {
 }
 
@@ -835,7 +849,7 @@
     return false;
 }
 
-void RenderThemeChromiumMac::adjustTextAreaStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderThemeChromiumMac::adjustTextAreaStyle(RenderStyle*, Element*) const
 {
 }
 
@@ -1040,7 +1054,7 @@
     return progressAnimationNumFrames * progressAnimationFrameRate;
 }
 
-void RenderThemeChromiumMac::adjustProgressBarStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderThemeChromiumMac::adjustProgressBarStyle(RenderStyle*, Element*) const
 {
 }
 
@@ -1093,7 +1107,7 @@
         paintInfo.context->scale(FloatSize(-1, 1));
     }
 
-    paintInfo.context->drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, inflatedRect.location());
+    paintInfo.context->drawImageBuffer(imageBuffer.get(), inflatedRect.location());
     return false;
 }
 
@@ -1238,7 +1252,7 @@
 
     GraphicsContextStateSaver stateSaver(*paintInfo.context);
 
-    paintInfo.context->setFillColor(o->style()->visitedDependentColor(CSSPropertyColor), o->style()->colorSpace());
+    paintInfo.context->setFillColor(o->style()->visitedDependentColor(CSSPropertyColor));
     paintInfo.context->setStrokeStyle(NoStroke);
 
     FloatPoint arrow1[3];
@@ -1267,11 +1281,11 @@
     // Draw the separator to the left of the arrows
     paintInfo.context->setStrokeThickness(1.0f); // Deliberately ignores zoom since it looks nicer if it stays thin.
     paintInfo.context->setStrokeStyle(SolidStroke);
-    paintInfo.context->setStrokeColor(leftSeparatorColor, ColorSpaceDeviceRGB);
+    paintInfo.context->setStrokeColor(leftSeparatorColor);
     paintInfo.context->drawLine(IntPoint(leftEdgeOfSeparator, bounds.y()),
                                 IntPoint(leftEdgeOfSeparator, bounds.maxY()));
 
-    paintInfo.context->setStrokeColor(rightSeparatorColor, ColorSpaceDeviceRGB);
+    paintInfo.context->setStrokeColor(rightSeparatorColor);
     paintInfo.context->drawLine(IntPoint(leftEdgeOfSeparator + separatorSpace, bounds.y()),
                                 IntPoint(leftEdgeOfSeparator + separatorSpace, bounds.maxY()));
     return false;
@@ -1283,7 +1297,7 @@
     return sizes;
 }
 
-void RenderThemeChromiumMac::adjustMenuListStyle(StyleResolver* styleResolver, RenderStyle* style, Element* e) const
+void RenderThemeChromiumMac::adjustMenuListStyle(RenderStyle* style, Element* e) const
 {
     NSControlSize controlSize = controlSizeForFont(style);
 
@@ -1306,7 +1320,7 @@
     // Our font is locked to the appropriate system font size for the control.  To clarify, we first use the CSS-specified font to figure out
     // a reasonable control size, but once that control size is determined, we throw that font away and use the appropriate
     // system font for the control size instead.
-    setFontFromControlSize(styleResolver, style, controlSize);
+    setFontFromControlSize(style, controlSize);
 }
 
 const int autofillPopupHorizontalPadding = 4;
@@ -1360,7 +1374,7 @@
     return 0;
 }
 
-void RenderThemeChromiumMac::adjustMenuListButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumMac::adjustMenuListButtonStyle(RenderStyle* style, Element*) const
 {
     float fontScale = style->fontSize() / baseFontSize;
 
@@ -1509,9 +1523,10 @@
 bool RenderThemeChromiumMac::paintSearchField(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r)
 {
     LocalCurrentGraphicsContext localContext(paintInfo.context);
-    NSSearchFieldCell* search = this->search();
 
+    NSSearchFieldCell* search = this->search();
     setSearchCellState(o, r);
+    [search setControlSize:controlSizeForFont(o->style())];
 
     GraphicsContextStateSaver stateSaver(*paintInfo.context);
 
@@ -1542,8 +1557,6 @@
 {
     NSSearchFieldCell* search = this->search();
 
-    [search setControlSize:controlSizeForFont(o->style())];
-
     // Update the various states we respond to.
     updateActiveState(search, o);
     updateEnabledState(search, o);
@@ -1566,7 +1579,7 @@
     setSizeFromFont(style, searchFieldSizes());
 }
 
-void RenderThemeChromiumMac::adjustSearchFieldStyle(StyleResolver* styleResolver, RenderStyle* style, Element*) const
+void RenderThemeChromiumMac::adjustSearchFieldStyle(RenderStyle* style, Element*) const
 {
     // Override border.
     style->resetBorder();
@@ -1592,7 +1605,7 @@
     style->setPaddingBottom(Length(padding, Fixed));
 
     NSControlSize controlSize = controlSizeForFont(style);
-    setFontFromControlSize(styleResolver, style, controlSize);
+    setFontFromControlSize(style, controlSize);
 
     style->setBoxShadow(nullptr);
 }
@@ -1607,9 +1620,10 @@
         return false;
 
     LocalCurrentGraphicsContext localContext(paintInfo.context);
-    setSearchCellState(input->renderer(), r);
 
     NSSearchFieldCell* search = this->search();
+    setSearchCellState(input->renderer(), r);
+    [search setControlSize:cancelButtonControlSizeForFont(o->style())];
 
     if (!input->isDisabledFormControl() && (input->isTextFormControl() && !toHTMLTextFormControlElement(input)->isReadOnly())) {
         updateActiveState([search cancelButtonCell], o);
@@ -1621,21 +1635,7 @@
     GraphicsContextStateSaver stateSaver(*paintInfo.context);
 
     float zoomLevel = o->style()->effectiveZoom();
-
-    FloatRect localBounds = [search cancelButtonRectForBounds:NSRect(input->renderBox()->pixelSnappedBorderBoxRect())];
-
-#if ENABLE(INPUT_SPEECH)
-    // Take care of cases where the cancel button was not aligned with the right border of the input element (for e.g.
-    // when speech input is enabled for the input element.
-    IntRect absBoundingBox = input->renderer()->absoluteBoundingBoxRect();
-    int absRight = absBoundingBox.x() + absBoundingBox.width() - input->renderBox()->paddingRight() - input->renderBox()->borderRight();
-    int spaceToRightOfCancelButton = absRight - (r.x() + r.width());
-    localBounds.setX(localBounds.x() - spaceToRightOfCancelButton);
-#endif
-
-    localBounds = convertToPaintingRect(input->renderer(), o, localBounds, r);
-
-    FloatRect unzoomedRect(localBounds);
+    FloatRect unzoomedRect(r);
     if (zoomLevel != 1.0f) {
         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
@@ -1651,11 +1651,11 @@
 
 const IntSize* RenderThemeChromiumMac::cancelButtonSizes() const
 {
-    static const IntSize sizes[3] = { IntSize(16, 13), IntSize(13, 11), IntSize(13, 9) };
+    static const IntSize sizes[3] = { IntSize(16, 14), IntSize(13, 11), IntSize(13, 9) };
     return sizes;
 }
 
-void RenderThemeChromiumMac::adjustSearchFieldCancelButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumMac::adjustSearchFieldCancelButtonStyle(RenderStyle* style, Element*) const
 {
     IntSize size = sizeForSystemFont(style, cancelButtonSizes());
     style->setWidth(Length(size.width(), Fixed));
@@ -1670,7 +1670,7 @@
 }
 
 const int emptyResultsOffset = 9;
-void RenderThemeChromiumMac::adjustSearchFieldDecorationStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumMac::adjustSearchFieldDecorationStyle(RenderStyle* style, Element*) const
 {
     IntSize size = sizeForSystemFont(style, resultsButtonSizes());
     style->setWidth(Length(size.width() - emptyResultsOffset, Fixed));
@@ -1683,7 +1683,7 @@
     return false;
 }
 
-void RenderThemeChromiumMac::adjustSearchFieldResultsDecorationStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumMac::adjustSearchFieldResultsDecorationStyle(RenderStyle* style, Element*) const
 {
     IntSize size = sizeForSystemFont(style, resultsButtonSizes());
     style->setWidth(Length(size.width(), Fixed));
@@ -1700,9 +1700,10 @@
         return false;
 
     LocalCurrentGraphicsContext localContext(paintInfo.context);
-    setSearchCellState(input->renderer(), r);
 
     NSSearchFieldCell* search = this->search();
+    setSearchCellState(input->renderer(), r);
+    [search setControlSize:controlSizeForFont(o->style())];
 
     if ([search searchMenuTemplate] != nil)
         [search setSearchMenuTemplate:nil];
diff --git a/Source/core/rendering/RenderThemeChromiumSkia.cpp b/Source/core/rendering/RenderThemeChromiumSkia.cpp
index a186743..ff22164 100644
--- a/Source/core/rendering/RenderThemeChromiumSkia.cpp
+++ b/Source/core/rendering/RenderThemeChromiumSkia.cpp
@@ -137,9 +137,9 @@
     return caretBlinkIntervalInternal();
 }
 
-void RenderThemeChromiumSkia::systemFont(int propId, FontDescription& fontDescription) const
+void RenderThemeChromiumSkia::systemFont(CSSValueID valueID, FontDescription& fontDescription) const
 {
-    RenderThemeChromiumFontProvider::systemFont(propId, fontDescription);
+    RenderThemeChromiumFontProvider::systemFont(valueID, fontDescription);
 }
 
 int RenderThemeChromiumSkia::minimumMenuListSize(RenderStyle* style) const
@@ -184,7 +184,7 @@
     setCheckboxSize(style);
 }
 
-void RenderThemeChromiumSkia::adjustButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumSkia::adjustButtonStyle(RenderStyle* style, Element*) const
 {
     if (style->appearance() == PushButtonPart) {
         // Ignore line-height.
@@ -197,7 +197,7 @@
     return paintTextField(o, i, r);
 }
 
-void RenderThemeChromiumSkia::adjustSearchFieldStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumSkia::adjustSearchFieldStyle(RenderStyle* style, Element*) const
 {
      // Ignore line-height.
      style->setLineHeight(RenderStyle::initialLineHeight());
@@ -208,7 +208,7 @@
     return paintTextField(o, i, r);
 }
 
-void RenderThemeChromiumSkia::adjustSearchFieldCancelButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumSkia::adjustSearchFieldCancelButtonStyle(RenderStyle* style, Element*) const
 {
     // Scale the button size based on the font size
     float fontScale = style->fontSize() / defaultControlFontPixelSize;
@@ -251,19 +251,18 @@
 
     static Image* cancelImage = Image::loadPlatformResource("searchCancel").leakRef();
     static Image* cancelPressedImage = Image::loadPlatformResource("searchCancelPressed").leakRef();
-    paintInfo.context->drawImage(isPressed(cancelButtonObject) ? cancelPressedImage : cancelImage,
-                                 cancelButtonObject->style()->colorSpace(), paintingRect);
+    paintInfo.context->drawImage(isPressed(cancelButtonObject) ? cancelPressedImage : cancelImage, paintingRect);
     return false;
 }
 
-void RenderThemeChromiumSkia::adjustSearchFieldDecorationStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumSkia::adjustSearchFieldDecorationStyle(RenderStyle* style, Element*) const
 {
     IntSize emptySize(1, 11);
     style->setWidth(Length(emptySize.width(), Fixed));
     style->setHeight(Length(emptySize.height(), Fixed));
 }
 
-void RenderThemeChromiumSkia::adjustSearchFieldResultsDecorationStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumSkia::adjustSearchFieldResultsDecorationStyle(RenderStyle* style, Element*) const
 {
     // Scale the decoration size based on the font size
     float fontScale = style->fontSize() / defaultControlFontPixelSize;
@@ -294,7 +293,7 @@
     IntRect paintingRect = convertToPaintingRect(inputRenderBox, magnifierObject, magnifierRect, r);
 
     static Image* magnifierImage = Image::loadPlatformResource("searchMagnifier").leakRef();
-    paintInfo.context->drawImage(magnifierImage, magnifierObject->style()->colorSpace(), paintingRect);
+    paintInfo.context->drawImage(magnifierImage, paintingRect);
     return false;
 }
 
@@ -353,15 +352,15 @@
     return RenderMediaControlsChromium::paintMediaControlsPart(MediaEnterFullscreenButton, object, paintInfo, rect);
 }
 
-void RenderThemeChromiumSkia::adjustMenuListStyle(StyleResolver*, RenderStyle* style, WebCore::Element*) const
+void RenderThemeChromiumSkia::adjustMenuListStyle(RenderStyle* style, WebCore::Element*) const
 {
     // Height is locked to auto on all browsers.
     style->setLineHeight(RenderStyle::initialLineHeight());
 }
 
-void RenderThemeChromiumSkia::adjustMenuListButtonStyle(StyleResolver* styleResolver, RenderStyle* style, Element* e) const
+void RenderThemeChromiumSkia::adjustMenuListButtonStyle(RenderStyle* style, Element* e) const
 {
-    adjustMenuListStyle(styleResolver, style, e);
+    adjustMenuListStyle(style, e);
 }
 
 // Used to paint styled menulists (i.e. with a non-default border)
diff --git a/Source/core/rendering/RenderThemeChromiumSkia.h b/Source/core/rendering/RenderThemeChromiumSkia.h
index 6894264..3a081f6 100644
--- a/Source/core/rendering/RenderThemeChromiumSkia.h
+++ b/Source/core/rendering/RenderThemeChromiumSkia.h
@@ -66,7 +66,7 @@
     virtual double caretBlinkInterval() const;
 
     // System fonts.
-    virtual void systemFont(int propId, FontDescription&) const;
+    virtual void systemFont(CSSValueID, FontDescription&) const;
 
     virtual int minimumMenuListSize(RenderStyle*) const;
 
@@ -74,19 +74,19 @@
 
     virtual void setRadioSize(RenderStyle*) const;
 
-    virtual void adjustButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustButtonStyle(RenderStyle*, Element*) const;
 
     virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&);
 
-    virtual void adjustSearchFieldStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchField(RenderObject*, const PaintInfo&, const IntRect&);
 
-    virtual void adjustSearchFieldCancelButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldCancelButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchFieldCancelButton(RenderObject*, const PaintInfo&, const IntRect&);
 
-    virtual void adjustSearchFieldDecorationStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldDecorationStyle(RenderStyle*, Element*) const;
 
-    virtual void adjustSearchFieldResultsDecorationStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&);
 
     virtual bool paintMediaSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
@@ -110,8 +110,8 @@
     // In short, we either go down the MenuList code path or the MenuListButton
     // codepath. We never go down both. And in both cases, they render the
     // entire menulist.
-    virtual void adjustMenuListStyle(StyleResolver*, RenderStyle*, Element*) const;
-    virtual void adjustMenuListButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
+    virtual void adjustMenuListStyle(RenderStyle*, Element*) const;
+    virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&);
 
     virtual double animationRepeatIntervalForProgressBar(RenderProgress*) const;
diff --git a/Source/core/rendering/RenderThemeChromiumWin.cpp b/Source/core/rendering/RenderThemeChromiumWin.cpp
index 3e9ddc7..2a25607 100644
--- a/Source/core/rendering/RenderThemeChromiumWin.cpp
+++ b/Source/core/rendering/RenderThemeChromiumWin.cpp
@@ -44,10 +44,10 @@
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderProgress.h"
 #include "core/rendering/RenderSlider.h"
-#include <public/Platform.h>
-#include <public/WebColor.h>
-#include <public/WebRect.h>
-#include <public/win/WebThemeEngine.h>
+#include "public/platform/Platform.h"
+#include "public/platform/WebColor.h"
+#include "public/platform/WebRect.h"
+#include "public/platform/win/WebThemeEngine.h"
 #include <wtf/CurrentTime.h>
 
 
@@ -254,7 +254,7 @@
     }
 }
 
-Color RenderThemeChromiumWin::systemColor(int cssValueId) const
+Color RenderThemeChromiumWin::systemColor(CSSValueID cssValueId) const
 {
     int sysColorIndex = cssValueIdToSysColorIndex(cssValueId);
     if (isRunningLayoutTest() || (sysColorIndex == -1))
@@ -582,7 +582,7 @@
     return false;
 }
 
-void RenderThemeChromiumWin::adjustInnerSpinButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
+void RenderThemeChromiumWin::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const
 {
     int width = ScrollbarTheme::theme()->scrollbarThickness();
     style->setWidth(Length(width, Fixed));
@@ -628,7 +628,7 @@
     return progressAnimationFrameRate;
 }
 
-void RenderThemeChromiumWin::adjustProgressBarStyle(StyleResolver*, RenderStyle*, Element*) const
+void RenderThemeChromiumWin::adjustProgressBarStyle(RenderStyle*, Element*) const
 {
 }
 
diff --git a/Source/core/rendering/RenderThemeChromiumWin.h b/Source/core/rendering/RenderThemeChromiumWin.h
index d22b338..2b59a22 100644
--- a/Source/core/rendering/RenderThemeChromiumWin.h
+++ b/Source/core/rendering/RenderThemeChromiumWin.h
@@ -57,7 +57,7 @@
     virtual Color platformActiveTextSearchHighlightColor() const OVERRIDE;
     virtual Color platformInactiveTextSearchHighlightColor() const OVERRIDE;
 
-    virtual Color systemColor(int cssValueId) const OVERRIDE;
+    virtual Color systemColor(CSSValueID) const OVERRIDE;
 
     virtual IntSize sliderTickSize() const OVERRIDE;
     virtual int sliderTickOffsetFromTrackCenter() const OVERRIDE;
@@ -77,12 +77,12 @@
     virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
     virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual void adjustInnerSpinButtonStyle(StyleResolver*, RenderStyle*, Element*) const OVERRIDE;
+    virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const OVERRIDE;
     virtual bool paintInnerSpinButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
     virtual double animationRepeatIntervalForProgressBar(RenderProgress*) const OVERRIDE;
     virtual double animationDurationForProgressBar(RenderProgress*) const OVERRIDE;
-    virtual void adjustProgressBarStyle(StyleResolver*, RenderStyle*, Element*) const OVERRIDE;
+    virtual void adjustProgressBarStyle(RenderStyle*, Element*) const OVERRIDE;
     virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
     virtual bool shouldOpenPickerWithF4Key() const OVERRIDE;
diff --git a/Source/core/rendering/RenderVideo.cpp b/Source/core/rendering/RenderVideo.cpp
index 439b1a0..61ce56c 100644
--- a/Source/core/rendering/RenderVideo.cpp
+++ b/Source/core/rendering/RenderVideo.cpp
@@ -49,8 +49,6 @@
 
 RenderVideo::~RenderVideo()
 {
-    if (MediaPlayer* p = mediaElement()->player())
-        p->setVisible(false);
 }
 
 IntSize RenderVideo::defaultSize()
@@ -239,16 +237,10 @@
     if (!mediaPlayer)
         return;
 
-    if (!videoElement()->inActiveDocument()) {
-        mediaPlayer->setVisible(false);
+    if (!videoElement()->inActiveDocument())
         return;
-    }
 
     contentChanged(VideoChanged);
-    
-    IntRect videoBounds = videoBox(); 
-    mediaPlayer->setSize(IntSize(videoBounds.width(), videoBounds.height()));
-    mediaPlayer->setVisible(true);
 }
 
 LayoutUnit RenderVideo::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
diff --git a/Source/core/rendering/RenderView.cpp b/Source/core/rendering/RenderView.cpp
index 78259d0..32d63a0 100644
--- a/Source/core/rendering/RenderView.cpp
+++ b/Source/core/rendering/RenderView.cpp
@@ -262,7 +262,7 @@
     if (relayoutChildren) {
         setChildNeedsLayout(true, MarkOnlyThis);
         for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
-            if ((child->isBox() && (toRenderBox(child)->hasRelativeLogicalHeight() || toRenderBox(child)->hasViewportPercentageLogicalHeight()))
+            if ((child->isBox() && toRenderBox(child)->hasRelativeLogicalHeight())
                     || child->style()->logicalHeight().isPercent()
                     || child->style()->logicalMinHeight().isPercent()
                     || child->style()->logicalMaxHeight().isPercent()
@@ -381,9 +381,11 @@
     // RenderViews should never be called to paint with an offset not on device pixels.
     ASSERT(LayoutPoint(IntPoint(paintOffset.x(), paintOffset.y())) == paintOffset);
 
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     // This avoids painting garbage between columns if there is a column gap.
     if (m_frameView && m_frameView->pagination().mode != Pagination::Unpaginated)
-        paintInfo.context->fillRect(paintInfo.rect, m_frameView->baseBackgroundColor(), ColorSpaceDeviceRGB);
+        paintInfo.context->fillRect(paintInfo.rect, m_frameView->baseBackgroundColor());
 
     paintObject(paintInfo, paintOffset);
 }
@@ -430,10 +432,8 @@
         }
 
         if (RenderLayer* compositingLayer = layer->enclosingCompositingLayerForRepaint()) {
-            if (!compositingLayer->backing()->paintsIntoWindow()) {
-                frameView()->setCannotBlitToWindow();
-                break;
-            }
+            frameView()->setCannotBlitToWindow();
+            break;
         }
     }
 
@@ -471,7 +471,7 @@
         if (baseColor.alpha()) {
             CompositeOperator previousOperator = paintInfo.context->compositeOperation();
             paintInfo.context->setCompositeOperation(CompositeCopy);
-            paintInfo.context->fillRect(paintInfo.rect, baseColor, style()->colorSpace());
+            paintInfo.context->fillRect(paintInfo.rect, baseColor);
             paintInfo.context->setCompositeOperation(previousOperator);
         } else
             paintInfo.context->clearRect(paintInfo.rect);
@@ -643,9 +643,8 @@
 
         // Blocks are responsible for painting line gaps and margin gaps. They must be examined as well.
         for (RenderBlock* block = o->containingBlock(); block && !block->isRenderView(); block = block->containingBlock()) {
-            if (processedBlocks.contains(block))
+            if (!processedBlocks.add(block).isNewEntry)
                 break;
-            processedBlocks.add(block);
             RenderSelectionInfo(block, true).repaint();
         }
     }
@@ -1083,6 +1082,17 @@
     return m_intervalArena.get();
 }
 
+bool RenderView::backgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const
+{
+    // FIXME: Remove this main frame check. Same concept applies to subframes too.
+    Page* page = document()->page();
+    Frame* mainFrame = page ? page->mainFrame() : 0;
+    if (!m_frameView || m_frameView->frame() != mainFrame)
+        return false;
+
+    return m_frameView->hasOpaqueBackground();
+}
+
 void RenderView::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
 {
     MemoryClassInfo info(memoryObjectInfo, this, PlatformMemoryTypes::Rendering);
diff --git a/Source/core/rendering/RenderView.h b/Source/core/rendering/RenderView.h
index 737ba9f..3b93e29 100644
--- a/Source/core/rendering/RenderView.h
+++ b/Source/core/rendering/RenderView.h
@@ -196,6 +196,8 @@
     
     virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0) OVERRIDE;
 
+    virtual bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const OVERRIDE FINAL;
+
 protected:
     virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE;
     virtual const RenderObject* pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&) const OVERRIDE;
diff --git a/Source/core/rendering/RenderWidget.cpp b/Source/core/rendering/RenderWidget.cpp
index 3f1a800..2d76543 100644
--- a/Source/core/rendering/RenderWidget.cpp
+++ b/Source/core/rendering/RenderWidget.cpp
@@ -202,6 +202,9 @@
         }
         moveWidgetToParentSoon(m_widget.get(), m_frameView);
     }
+
+    if (AXObjectCache* cache = document()->existingAXObjectCache())
+        cache->childrenChanged(this);
 }
 
 void RenderWidget::layout()
@@ -258,6 +261,8 @@
 
 void RenderWidget::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     if (!shouldPaint(paintInfo, paintOffset))
         return;
 
@@ -299,7 +304,7 @@
     // Paint a partially transparent wash over selected widgets.
     if (isSelected() && !document()->printing()) {
         // FIXME: selectionRect() is in absolute, not painting coordinates.
-        paintInfo.context->fillRect(pixelSnappedIntRect(selectionRect()), selectionBackgroundColor(), style()->colorSpace());
+        paintInfo.context->fillRect(pixelSnappedIntRect(selectionRect()), selectionBackgroundColor());
     }
 
     if (hasLayer() && layer()->canResize())
diff --git a/Source/core/rendering/RootInlineBox.cpp b/Source/core/rendering/RootInlineBox.cpp
index d6367fc..b2e5a31 100644
--- a/Source/core/rendering/RootInlineBox.cpp
+++ b/Source/core/rendering/RootInlineBox.cpp
@@ -464,7 +464,7 @@
                 LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
                 if (isPreviousBoxSelected && gapRect.width() > 0 && gapRect.height() > 0) {
                     if (paintInfo && box->parent()->renderer()->style()->visibility() == VISIBLE)
-                        paintInfo->context->fillRect(gapRect, box->parent()->renderer()->selectionBackgroundColor(), box->parent()->renderer()->style()->colorSpace());
+                        paintInfo->context->fillRect(gapRect, box->parent()->renderer()->selectionBackgroundColor());
                     // VisibleSelection may be non-contiguous, see comment above.
                     result.uniteCenter(gapRect);
                 }
diff --git a/Source/core/rendering/TextAutosizer.cpp b/Source/core/rendering/TextAutosizer.cpp
index d34593f..948115d 100644
--- a/Source/core/rendering/TextAutosizer.cpp
+++ b/Source/core/rendering/TextAutosizer.cpp
@@ -351,7 +351,8 @@
         || renderer->hasColumns()
         || renderer->containingBlock()->isHorizontalWritingMode() != renderer->isHorizontalWritingMode()
         || renderer->style()->isDisplayReplacedType()
-        || renderer->isTextArea();
+        || renderer->isTextArea()
+        || renderer->style()->userModify() != READ_ONLY;
     // FIXME: Tables need special handling to multiply all their columns by
     // the same amount even if they're different widths; so do hasColumns()
     // containers, and probably flexboxes...
@@ -446,12 +447,12 @@
         RenderStyle* style = container->style();
         if (style->overflowY() >= OSCROLL)
             return false;
-        if (style->height().isSpecified() || style->maxHeight().isSpecified()) {
+        if (style->height().isSpecified() || style->maxHeight().isSpecified() || container->isOutOfFlowPositioned()) {
             // Some sites (e.g. wikipedia) set their html and/or body elements to height:100%,
             // without intending to constrain the height of the content within them.
             return !container->isRoot() && !container->isBody();
         }
-        if (container->isFloatingOrOutOfFlowPositioned())
+        if (container->isFloating())
             return false;
     }
     return false;
@@ -476,15 +477,15 @@
     // in and pan from side to side to read each line, since if there are very
     // few lines of text you'll only need to pan across once or twice.
     //
-    // An exception to the 4 lines of text are the textarea clusters, which are
-    // always autosized by default (i.e. threated as if they contain more than 4
-    // lines of text). This is to ensure that the text does not suddenly get
-    // autosized when the user enters more than 4 lines of text.
+    // An exception to the 4 lines of text are the textarea and contenteditable
+    // clusters, which are always autosized by default (i.e. threated as if they
+    // contain more than 4 lines of text). This is to ensure that the text does
+    // not suddenly get autosized when the user enters more than 4 lines of text.
     float totalTextWidth = 0;
     const float minLinesOfText = 4;
     float minTextWidth = blockWidth * minLinesOfText;
     for (size_t i = 0; i < clusterInfos.size(); ++i) {
-        if (clusterInfos[i].root->isTextArea())
+        if (clusterInfos[i].root->isTextArea() || (clusterInfos[i].root->style() && clusterInfos[i].root->style()->userModify() != READ_ONLY))
             return true;
         measureDescendantTextWidth(clusterInfos[i].blockContainingAllText, clusterInfos[i], minTextWidth, totalTextWidth);
         if (totalTextWidth >= minTextWidth)
diff --git a/Source/core/rendering/exclusions/ExclusionShape.cpp b/Source/core/rendering/exclusions/ExclusionShape.cpp
index 90cbba9..23d216d 100644
--- a/Source/core/rendering/exclusions/ExclusionShape.cpp
+++ b/Source/core/rendering/exclusions/ExclusionShape.cpp
@@ -100,7 +100,7 @@
 
     switch (basicShape->type()) {
 
-    case BasicShape::BASIC_SHAPE_RECTANGLE: {
+    case BasicShape::BasicShapeRectangleType: {
         const BasicShapeRectangle* rectangle = static_cast<const BasicShapeRectangle*>(basicShape);
         FloatRect bounds(
             floatValueForLength(rectangle->x(), boxWidth),
@@ -118,7 +118,7 @@
         break;
     }
 
-    case BasicShape::BASIC_SHAPE_CIRCLE: {
+    case BasicShape::BasicShapeCircleType: {
         const BasicShapeCircle* circle = static_cast<const BasicShapeCircle*>(basicShape);
         float centerX = floatValueForLength(circle->centerX(), boxWidth);
         float centerY = floatValueForLength(circle->centerY(), boxHeight);
@@ -129,7 +129,7 @@
         break;
     }
 
-    case BasicShape::BASIC_SHAPE_ELLIPSE: {
+    case BasicShape::BasicShapeEllipseType: {
         const BasicShapeEllipse* ellipse = static_cast<const BasicShapeEllipse*>(basicShape);
         float centerX = floatValueForLength(ellipse->centerX(), boxWidth);
         float centerY = floatValueForLength(ellipse->centerY(), boxHeight);
@@ -142,7 +142,7 @@
         break;
     }
 
-    case BasicShape::BASIC_SHAPE_POLYGON: {
+    case BasicShape::BasicShapePolygonType: {
         const BasicShapePolygon* polygon = static_cast<const BasicShapePolygon*>(basicShape);
         const Vector<Length>& values = polygon->values();
         size_t valuesSize = values.size();
diff --git a/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp b/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp
index b292a43..69e2a41 100644
--- a/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp
+++ b/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp
@@ -30,8 +30,8 @@
 #include "config.h"
 #include "core/rendering/exclusions/ExclusionShapeInfo.h"
 
-#include "core/rendering/exclusions/ExclusionShape.h"
 #include "core/rendering/RenderRegion.h"
+#include "core/rendering/exclusions/ExclusionShape.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
@@ -42,7 +42,7 @@
         return exclusionShape;
 
     ExclusionShapeValue* shapeValue = (m_renderer->style()->*shapeGetter)();
-    BasicShape* shape = (shapeValue && shapeValue->type() == ExclusionShapeValue::SHAPE) ? shapeValue->shape() : 0;
+    BasicShape* shape = (shapeValue && shapeValue->type() == ExclusionShapeValue::Shape) ? shapeValue->shape() : 0;
 
     ASSERT(shape);
 
diff --git a/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp b/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp
index 9f681d5..210649a 100644
--- a/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp
+++ b/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp
@@ -44,7 +44,11 @@
 bool ExclusionShapeInsideInfo::isEnabledFor(const RenderBlock* renderer)
 {
     ExclusionShapeValue* shapeValue = renderer->style()->resolvedShapeInside();
-    return (shapeValue && shapeValue->type() == ExclusionShapeValue::SHAPE) ? shapeValue->shape() : 0;
+    if (!shapeValue || shapeValue->type() != ExclusionShapeValue::Shape)
+        return false;
+
+    BasicShape* shape = shapeValue->shape();
+    return shape && shape->type() != BasicShape::BasicShapeInsetRectangleType;
 }
 
 bool ExclusionShapeInsideInfo::adjustLogicalLineTop(float minSegmentWidth)
diff --git a/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp b/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp
index 89d1fc1..3e2b631 100644
--- a/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp
+++ b/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp
@@ -36,7 +36,11 @@
 bool ExclusionShapeOutsideInfo::isEnabledFor(const RenderBox* box)
 {
     ExclusionShapeValue* value = box->style()->shapeOutside();
-    return (box->isFloatingWithShapeOutside() && value->type() == ExclusionShapeValue::SHAPE) ? value->shape() : 0;
+    if (!box->isFloatingWithShapeOutside() || value->type() != ExclusionShapeValue::Shape)
+        return false;
+
+    BasicShape* shape = value->shape();
+    return shape && shape->type() != BasicShape::BasicShapeInsetRectangleType;
 }
 
 bool ExclusionShapeOutsideInfo::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
diff --git a/Source/core/rendering/style/BasicShapes.cpp b/Source/core/rendering/style/BasicShapes.cpp
index efef136..31173e8 100644
--- a/Source/core/rendering/style/BasicShapes.cpp
+++ b/Source/core/rendering/style/BasicShapes.cpp
@@ -43,7 +43,7 @@
         return false;
 
     // Just polygons with same number of vertices can be animated.
-    if (type() == BasicShape::BASIC_SHAPE_POLYGON
+    if (type() == BasicShape::BasicShapePolygonType
         && static_cast<const BasicShapePolygon*>(this)->values().size() != static_cast<const BasicShapePolygon*>(other)->values().size())
         return false;
 
@@ -53,12 +53,18 @@
 void BasicShapeRectangle::path(Path& path, const FloatRect& boundingBox)
 {
     ASSERT(path.isEmpty());
-    path.addRoundedRect(FloatRect(floatValueForLength(m_x, boundingBox.width()) + boundingBox.x(),
-                                  floatValueForLength(m_y, boundingBox.height()) + boundingBox.y(),
-                                  floatValueForLength(m_width, boundingBox.width()),
-                                  floatValueForLength(m_height, boundingBox.height())),
-                        FloatSize(m_cornerRadiusX.isUndefined() ? 0 : floatValueForLength(m_cornerRadiusX, boundingBox.width()),
-                                  m_cornerRadiusY.isUndefined() ? 0 : floatValueForLength(m_cornerRadiusY, boundingBox.height())));
+    path.addRoundedRect(
+        FloatRect(
+            floatValueForLength(m_x, boundingBox.width()) + boundingBox.x(),
+            floatValueForLength(m_y, boundingBox.height()) + boundingBox.y(),
+            floatValueForLength(m_width, boundingBox.width()),
+            floatValueForLength(m_height, boundingBox.height())
+        ),
+        FloatSize(
+            m_cornerRadiusX.isUndefined() ? 0 : floatValueForLength(m_cornerRadiusX, boundingBox.width()),
+            m_cornerRadiusY.isUndefined() ? 0 : floatValueForLength(m_cornerRadiusY, boundingBox.height())
+        )
+    );
 }
 
 PassRefPtr<BasicShape> BasicShapeRectangle::blend(const BasicShape* other, double progress) const
@@ -85,10 +91,12 @@
     float centerX = floatValueForLength(m_centerX, boundingBox.width());
     float centerY = floatValueForLength(m_centerY, boundingBox.height());
     float radius = floatValueForLength(m_radius, diagonal);
-    path.addEllipse(FloatRect(centerX - radius + boundingBox.x(),
-                              centerY - radius + boundingBox.y(),
-                              radius * 2,
-                              radius * 2));
+    path.addEllipse(FloatRect(
+        centerX - radius + boundingBox.x(),
+        centerY - radius + boundingBox.y(),
+        radius * 2,
+        radius * 2
+    ));
 }
 
 PassRefPtr<BasicShape> BasicShapeCircle::blend(const BasicShape* other, double progress) const
@@ -110,10 +118,12 @@
     float centerY = floatValueForLength(m_centerY, boundingBox.height());
     float radiusX = floatValueForLength(m_radiusX, boundingBox.width());
     float radiusY = floatValueForLength(m_radiusY, boundingBox.height());
-    path.addEllipse(FloatRect(centerX - radiusX + boundingBox.x(),
-                              centerY - radiusY + boundingBox.y(),
-                              radiusX * 2,
-                              radiusY * 2));
+    path.addEllipse(FloatRect(
+        centerX - radiusX + boundingBox.x(),
+        centerY - radiusY + boundingBox.y(),
+        radiusX * 2,
+        radiusY * 2
+    ));
 }
 
 PassRefPtr<BasicShape> BasicShapeEllipse::blend(const BasicShape* other, double progress) const
@@ -169,4 +179,40 @@
 
     return result.release();
 }
+
+void BasicShapeInsetRectangle::path(Path& path, const FloatRect& boundingBox)
+{
+    ASSERT(path.isEmpty());
+    float left = floatValueForLength(m_left, boundingBox.width());
+    float top = floatValueForLength(m_top, boundingBox.height());
+    path.addRoundedRect(
+        FloatRect(
+            left + boundingBox.x(),
+            top + boundingBox.y(),
+            std::max<float>(boundingBox.width() - left - floatValueForLength(m_right, boundingBox.width()), 0),
+            std::max<float>(boundingBox.height() - top - floatValueForLength(m_bottom, boundingBox.height()), 0)
+        ),
+        FloatSize(
+            m_cornerRadiusX.isUndefined() ? 0 : floatValueForLength(m_cornerRadiusX, boundingBox.width()),
+            m_cornerRadiusY.isUndefined() ? 0 : floatValueForLength(m_cornerRadiusY, boundingBox.height())
+        )
+    );
+}
+
+PassRefPtr<BasicShape> BasicShapeInsetRectangle::blend(const BasicShape* other, double progress) const
+{
+    ASSERT(type() == other->type());
+
+    const BasicShapeInsetRectangle* o = static_cast<const BasicShapeInsetRectangle*>(other);
+    RefPtr<BasicShapeInsetRectangle> result =  BasicShapeInsetRectangle::create();
+    result->setTop(m_top.blend(o->top(), progress));
+    result->setRight(m_right.blend(o->right(), progress));
+    result->setBottom(m_bottom.blend(o->bottom(), progress));
+    result->setLeft(m_left.blend(o->left(), progress));
+    if (!m_cornerRadiusX.isUndefined() && !o->cornerRadiusX().isUndefined())
+        result->setCornerRadiusX(m_cornerRadiusX.blend(o->cornerRadiusX(), progress));
+    if (!m_cornerRadiusY.isUndefined() && !o->cornerRadiusY().isUndefined())
+        result->setCornerRadiusY(m_cornerRadiusY.blend(o->cornerRadiusY(), progress));
+    return result.release();
+}
 }
diff --git a/Source/core/rendering/style/BasicShapes.h b/Source/core/rendering/style/BasicShapes.h
index 656f523..00db38d 100644
--- a/Source/core/rendering/style/BasicShapes.h
+++ b/Source/core/rendering/style/BasicShapes.h
@@ -46,10 +46,11 @@
     virtual ~BasicShape() { }
 
     enum Type {
-        BASIC_SHAPE_RECTANGLE = 1,
-        BASIC_SHAPE_CIRCLE = 2,
-        BASIC_SHAPE_ELLIPSE = 3,
-        BASIC_SHAPE_POLYGON = 4
+        BasicShapeRectangleType = 1,
+        BasicShapeCircleType = 2,
+        BasicShapeEllipseType = 3,
+        BasicShapePolygonType = 4,
+        BasicShapeInsetRectangleType = 5
     };
 
     bool canBlend(const BasicShape*) const;
@@ -84,7 +85,7 @@
     virtual void path(Path&, const FloatRect&) OVERRIDE;
     virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
 
-    virtual Type type() const { return BASIC_SHAPE_RECTANGLE; }
+    virtual Type type() const { return BasicShapeRectangleType; }
 private:
     BasicShapeRectangle()
         : m_cornerRadiusX(Undefined)
@@ -114,7 +115,7 @@
     virtual void path(Path&, const FloatRect&) OVERRIDE;
     virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
 
-    virtual Type type() const { return BASIC_SHAPE_CIRCLE; }
+    virtual Type type() const { return BasicShapeCircleType; }
 private:
     BasicShapeCircle() { }
 
@@ -140,7 +141,7 @@
     virtual void path(Path&, const FloatRect&) OVERRIDE;
     virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
 
-    virtual Type type() const { return BASIC_SHAPE_ELLIPSE; } 
+    virtual Type type() const { return BasicShapeEllipseType; }
 private:
     BasicShapeEllipse() { }
 
@@ -166,7 +167,7 @@
 
     virtual WindRule windRule() const { return m_windRule; }
 
-    virtual Type type() const { return BASIC_SHAPE_POLYGON; }
+    virtual Type type() const { return BasicShapePolygonType; }
 private:
     BasicShapePolygon()
         : m_windRule(RULE_NONZERO)
@@ -175,5 +176,41 @@
     WindRule m_windRule;
     Vector<Length> m_values;
 };
+
+class BasicShapeInsetRectangle : public BasicShape {
+public:
+    static PassRefPtr<BasicShapeInsetRectangle> create() { return adoptRef(new BasicShapeInsetRectangle); }
+
+    Length top() const { return m_top; }
+    Length right() const { return m_right; }
+    Length bottom() const { return m_bottom; }
+    Length left() const { return m_left; }
+    Length cornerRadiusX() const { return m_cornerRadiusX; }
+    Length cornerRadiusY() const { return m_cornerRadiusY; }
+
+    void setTop(Length top) { m_top = top; }
+    void setRight(Length right) { m_right = right; }
+    void setBottom(Length bottom) { m_bottom = bottom; }
+    void setLeft(Length left) { m_left = left; }
+    void setCornerRadiusX(Length radiusX) { m_cornerRadiusX = radiusX; }
+    void setCornerRadiusY(Length radiusY) { m_cornerRadiusY = radiusY; }
+
+    virtual void path(Path&, const FloatRect&) OVERRIDE;
+    virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
+
+    virtual Type type() const { return BasicShapeInsetRectangleType; }
+private:
+    BasicShapeInsetRectangle()
+        : m_cornerRadiusX(Undefined)
+        , m_cornerRadiusY(Undefined)
+    { }
+
+    Length m_right;
+    Length m_top;
+    Length m_bottom;
+    Length m_left;
+    Length m_cornerRadiusX;
+    Length m_cornerRadiusY;
+};
 }
 #endif
diff --git a/Source/core/rendering/style/ExclusionShapeValue.h b/Source/core/rendering/style/ExclusionShapeValue.h
index 874ad3c..c7ee9fa 100644
--- a/Source/core/rendering/style/ExclusionShapeValue.h
+++ b/Source/core/rendering/style/ExclusionShapeValue.h
@@ -31,16 +31,18 @@
 #define ExclusionShapeValue_h
 
 #include "core/rendering/style/BasicShapes.h"
-#include <wtf/PassRefPtr.h>
+#include "core/rendering/style/StyleImage.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
 class ExclusionShapeValue : public RefCounted<ExclusionShapeValue> {
 public:
     enum ExclusionShapeValueType {
-        // The AUTO value is defined by a null ExclusionShapeValue*
-        SHAPE,
-        OUTSIDE
+        // The Auto value is defined by a null ExclusionShapeValue*
+        Shape,
+        Outside,
+        Image
     };
 
     static PassRefPtr<ExclusionShapeValue> createShapeValue(PassRefPtr<BasicShape> shape)
@@ -50,18 +52,42 @@
 
     static PassRefPtr<ExclusionShapeValue> createOutsideValue()
     {
-        return adoptRef(new ExclusionShapeValue(OUTSIDE));
+        return adoptRef(new ExclusionShapeValue(Outside));
+    }
+
+    static PassRefPtr<ExclusionShapeValue> createImageValue(PassRefPtr<StyleImage> image)
+    {
+        return adoptRef(new ExclusionShapeValue(image));
     }
 
     ExclusionShapeValueType type() const { return m_type; }
     BasicShape* shape() const { return m_shape.get(); }
+    StyleImage* image() const { return m_image.get(); }
+    void setImage(PassRefPtr<StyleImage> image)
+    {
+        if (m_image != image)
+            m_image = image;
+    }
     bool operator==(const ExclusionShapeValue& other) const { return type() == other.type(); }
 
 private:
-    ExclusionShapeValue(PassRefPtr<BasicShape> shape) : m_type(SHAPE), m_shape(shape) { }
-    ExclusionShapeValue(ExclusionShapeValueType type) : m_type(type) { }
+    ExclusionShapeValue(PassRefPtr<BasicShape> shape)
+        : m_type(Shape)
+        , m_shape(shape)
+    {
+    }
+    ExclusionShapeValue(ExclusionShapeValueType type)
+        : m_type(type)
+    {
+    }
+    ExclusionShapeValue(PassRefPtr<StyleImage> image)
+        : m_type(Image)
+        , m_image(image)
+    {
+    }
     ExclusionShapeValueType m_type;
     RefPtr<BasicShape> m_shape;
+    RefPtr<StyleImage> m_image;
 };
 
 }
diff --git a/Source/core/rendering/style/RenderStyle.cpp b/Source/core/rendering/style/RenderStyle.cpp
index c76c82e..68a6d12 100644
--- a/Source/core/rendering/style/RenderStyle.cpp
+++ b/Source/core/rendering/style/RenderStyle.cpp
@@ -605,26 +605,15 @@
         || rareNonInheritedData->m_maskBoxImage != other->rareNonInheritedData->m_maskBoxImage)
         return StyleDifferenceRepaintLayer;
 
-    if (inherited->color != other->inherited->color
-        || inherited_flags._visibility != other->inherited_flags._visibility
-        || inherited_flags._text_decorations != other->inherited_flags._text_decorations
+    if (inherited_flags._visibility != other->inherited_flags._visibility
         || inherited_flags.m_printColorAdjust != other->inherited_flags.m_printColorAdjust
         || inherited_flags._insideLink != other->inherited_flags._insideLink
         || surround->border != other->surround->border
         || *m_background.get() != *other->m_background.get()
-        || visual->textDecoration != other->visual->textDecoration
         || rareInheritedData->userModify != other->rareInheritedData->userModify
         || rareInheritedData->userSelect != other->rareInheritedData->userSelect
         || rareNonInheritedData->userDrag != other->rareNonInheritedData->userDrag
         || rareNonInheritedData->m_borderFit != other->rareNonInheritedData->m_borderFit
-#if ENABLE(CSS3_TEXT)
-        || rareNonInheritedData->m_textDecorationStyle != other->rareNonInheritedData->m_textDecorationStyle
-        || rareNonInheritedData->m_textDecorationColor != other->rareNonInheritedData->m_textDecorationColor
-#endif // CSS3_TEXT
-        || rareInheritedData->textFillColor != other->rareInheritedData->textFillColor
-        || rareInheritedData->textStrokeColor != other->rareInheritedData->textStrokeColor
-        || rareInheritedData->textEmphasisColor != other->rareInheritedData->textEmphasisColor
-        || rareInheritedData->textEmphasisFill != other->rareInheritedData->textEmphasisFill
         || rareInheritedData->m_imageRendering != other->rareInheritedData->m_imageRendering)
         return StyleDifferenceRepaint;
         
@@ -648,6 +637,17 @@
             return StyleDifferenceRecompositeLayer;
     }
 
+    if (inherited->color != other->inherited->color
+        || inherited_flags._text_decorations != other->inherited_flags._text_decorations
+        || visual->textDecoration != other->visual->textDecoration
+        || rareNonInheritedData->m_textDecorationStyle != other->rareNonInheritedData->m_textDecorationStyle
+        || rareNonInheritedData->m_textDecorationColor != other->rareNonInheritedData->m_textDecorationColor
+        || rareInheritedData->textFillColor != other->rareInheritedData->textFillColor
+        || rareInheritedData->textStrokeColor != other->rareInheritedData->textStrokeColor
+        || rareInheritedData->textEmphasisColor != other->rareInheritedData->textEmphasisColor
+        || rareInheritedData->textEmphasisFill != other->rareInheritedData->textEmphasisFill)
+        return StyleDifferenceRepaintIfText;
+
     // Cursors are not checked, since they will be set appropriately in response to mouse events,
     // so they don't need to cause any repaint or layout.
 
@@ -1327,11 +1327,9 @@
     case CSSPropertyWebkitColumnRuleColor:
         result = visitedLink ? visitedLinkColumnRuleColor() : columnRuleColor();
         break;
-#if ENABLE(CSS3_TEXT)
-    case CSSPropertyWebkitTextDecorationColor:
+    case CSSPropertyTextDecorationColor:
         // Text decoration color fallback is handled in RenderObject::decorationColor.
         return visitedLink ? visitedLinkTextDecorationColor() : textDecorationColor();
-#endif // CSS3_TEXT
     case CSSPropertyWebkitTextEmphasisColor:
         result = visitedLink ? visitedLinkTextEmphasisColor() : textEmphasisColor();
         break;
@@ -1363,11 +1361,9 @@
 
     Color visitedColor = colorIncludingFallback(colorProperty, true);
 
-#if ENABLE(CSS3_TEXT)
     // Text decoration color validity is preserved (checked in RenderObject::decorationColor).
-    if (colorProperty == CSSPropertyWebkitTextDecorationColor)
+    if (colorProperty == CSSPropertyTextDecorationColor)
         return visitedColor;
-#endif // CSS3_TEXT
 
     // FIXME: Technically someone could explicitly specify the color transparent, but for now we'll just
     // assume that if the background color is transparent that it wasn't set. Note that it's weird that
diff --git a/Source/core/rendering/style/RenderStyle.h b/Source/core/rendering/style/RenderStyle.h
index 0507088..7238ded 100644
--- a/Source/core/rendering/style/RenderStyle.h
+++ b/Source/core/rendering/style/RenderStyle.h
@@ -35,7 +35,6 @@
 #include "core/platform/ThemeTypes.h"
 #include "core/platform/animation/CSSAnimationDataList.h"
 #include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/ColorSpace.h"
 #include "core/platform/graphics/FontBaseline.h"
 #include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/GraphicsTypes.h"
@@ -112,12 +111,12 @@
 class RenderStyle: public RefCounted<RenderStyle> {
     friend class CSSPropertyAnimation; // Used by CSS animations. We can't allow them to animate based off visited colors.
     friend class ApplyStyleCommand; // Editing has to only reveal unvisited info.
-    friend class DeprecatedStyleBuilder; // Sets members directly.
     friend class EditingStyle; // Editing has to only reveal unvisited info.
     friend class CSSComputedStyleDeclaration; // Ignores visited styles, so needs to be able to see unvisited info.
     friend class PropertyWrapperMaybeInvalidColor; // Used by CSS animations. We can't allow them to animate based off visited colors.
     friend class RenderSVGResource; // FIXME: Needs to alter the visited state by hand. Should clean the SVG code up and move it into RenderStyle perhaps.
     friend class RenderTreeAsText; // FIXME: Only needed so the render tree can keep lying and dump the wrong colors.  Rebaselining would allow this to be yanked.
+    friend class StyleBuilderFunctions; // Sets color styles
     friend class StyleResolver; // Sets members directly.
     friend class StyleResolverState; // Sets members directly.
 protected:
@@ -546,12 +545,10 @@
     TextDecoration textDecorationsInEffect() const { return static_cast<TextDecoration>(inherited_flags._text_decorations); }
     TextDecoration textDecoration() const { return static_cast<TextDecoration>(visual->textDecoration); }
 #if ENABLE(CSS3_TEXT)
-    TextDecorationStyle textDecorationStyle() const { return static_cast<TextDecorationStyle>(rareNonInheritedData->m_textDecorationStyle); }
     TextAlignLast textAlignLast() const { return static_cast<TextAlignLast>(rareInheritedData->m_textAlignLast); }
     TextUnderlinePosition textUnderlinePosition() const { return static_cast<TextUnderlinePosition>(rareInheritedData->m_textUnderlinePosition); }
-#else
-    TextDecorationStyle textDecorationStyle() const { return TextDecorationStyleSolid; }
 #endif // CSS3_TEXT
+    TextDecorationStyle textDecorationStyle() const { return static_cast<TextDecorationStyle>(rareNonInheritedData->m_textDecorationStyle); }
     int wordSpacing() const;
     int letterSpacing() const;
 
@@ -713,7 +710,6 @@
     void getTextShadowBlockDirectionExtent(LayoutUnit& logicalTop, LayoutUnit& logicalBottom) { getShadowBlockDirectionExtent(textShadow(), logicalTop, logicalBottom); }
 
     float textStrokeWidth() const { return rareInheritedData->textStrokeWidth; }
-    ColorSpace colorSpace() const { return static_cast<ColorSpace>(rareInheritedData->colorSpace); }
     float opacity() const { return rareNonInheritedData->opacity; }
     ControlPart appearance() const { return static_cast<ControlPart>(rareNonInheritedData->m_appearance); }
     // aspect ratio convenience method
@@ -1061,10 +1057,10 @@
     void setTextDecorationsInEffect(TextDecoration v) { inherited_flags._text_decorations = v; }
     void setTextDecoration(TextDecoration v) { SET_VAR(visual, textDecoration, v); }
 #if ENABLE(CSS3_TEXT)
-    void setTextDecorationStyle(TextDecorationStyle v) { SET_VAR(rareNonInheritedData, m_textDecorationStyle, v); }
     void setTextAlignLast(TextAlignLast v) { SET_VAR(rareInheritedData, m_textAlignLast, v); }
     void setTextUnderlinePosition(TextUnderlinePosition v) { SET_VAR(rareInheritedData, m_textUnderlinePosition, v); }
 #endif // CSS3_TEXT
+    void setTextDecorationStyle(TextDecorationStyle v) { SET_VAR(rareNonInheritedData, m_textDecorationStyle, v); }
     void setDirection(TextDirection v) { inherited_flags._direction = v; }
     void setLineHeight(Length specifiedLineHeight);
     bool setZoom(float);
@@ -1170,7 +1166,6 @@
     void setTextStrokeColor(const Color& c) { SET_VAR(rareInheritedData, textStrokeColor, c); }
     void setTextStrokeWidth(float w) { SET_VAR(rareInheritedData, textStrokeWidth, w); }
     void setTextFillColor(const Color& c) { SET_VAR(rareInheritedData, textFillColor, c); }
-    void setColorSpace(ColorSpace space) { SET_VAR(rareInheritedData, colorSpace, space); }
     void setOpacity(float f) { float v = clampTo<float>(f, 0, 1); SET_VAR(rareNonInheritedData, opacity, v); }
     void setAppearance(ControlPart a) { SET_VAR(rareNonInheritedData, m_appearance, a); }
     // For valid values of box-align see http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#alignment
@@ -1259,9 +1254,7 @@
     void setTransformOriginZ(float f) { SET_VAR(rareNonInheritedData.access()->m_transform, m_z, f); }
     void setSpeak(ESpeak s) { SET_VAR(rareInheritedData, speak, s); }
     void setTextCombine(TextCombine v) { SET_VAR(rareNonInheritedData, m_textCombine, v); }
-#if ENABLE(CSS3_TEXT)
     void setTextDecorationColor(const Color& c) { SET_VAR(rareNonInheritedData, m_textDecorationColor, c); }
-#endif // CSS3_TEXT
     void setTextEmphasisColor(const Color& c) { SET_VAR(rareInheritedData, textEmphasisColor, c); }
     void setTextEmphasisFill(TextEmphasisFill fill) { SET_VAR(rareInheritedData, textEmphasisFill, fill); }
     void setTextEmphasisMark(TextEmphasisMark mark) { SET_VAR(rareInheritedData, textEmphasisMark, mark); }
@@ -1372,7 +1365,7 @@
     ExclusionShapeValue* resolvedShapeInside() const
     {
         ExclusionShapeValue* shapeInside = this->shapeInside();
-        if (shapeInside && shapeInside->type() == ExclusionShapeValue::OUTSIDE)
+        if (shapeInside && shapeInside->type() == ExclusionShapeValue::Outside)
             return shapeOutside();
         return shapeInside;
     }
@@ -1473,7 +1466,6 @@
     static LengthSize initialBorderRadius() { return LengthSize(Length(0, Fixed), Length(0, Fixed)); }
     static ECaptionSide initialCaptionSide() { return CAPTOP; }
     static EClear initialClear() { return CNONE; }
-    static ColorSpace initialColorSpace() { return ColorSpaceDeviceRGB; }
     static ColumnAxis initialColumnAxis() { return AutoColumnAxis; }
     static ColumnProgression initialColumnProgression() { return NormalColumnProgression; }
     static TextDirection initialDirection() { return LTR; }
@@ -1520,10 +1512,10 @@
     static ETextAlign initialTextAlign() { return TASTART; }
     static TextDecoration initialTextDecoration() { return TextDecorationNone; }
 #if ENABLE(CSS3_TEXT)
-    static TextDecorationStyle initialTextDecorationStyle() { return TextDecorationStyleSolid; }
     static TextAlignLast initialTextAlignLast() { return TextAlignLastAuto; }
     static TextUnderlinePosition initialTextUnderlinePosition() { return TextUnderlinePositionAuto; }
 #endif // CSS3_TEXT
+    static TextDecorationStyle initialTextDecorationStyle() { return TextDecorationStyleSolid; }
     static float initialZoom() { return 1.0f; }
     static int initialOutlineOffset() { return 0; }
     static float initialOpacity() { return 1.0f; }
@@ -1657,9 +1649,7 @@
     void setVisitedLinkBorderTopColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderTopColor, v); }
     void setVisitedLinkOutlineColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkOutlineColor, v); }
     void setVisitedLinkColumnRuleColor(const Color& v) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_visitedLinkColumnRuleColor, v); }
-#if ENABLE(CSS3_TEXT)
     void setVisitedLinkTextDecorationColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkTextDecorationColor, v); }
-#endif // CSS3_TEXT
     void setVisitedLinkTextEmphasisColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextEmphasisColor, v); }
     void setVisitedLinkTextFillColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextFillColor, v); }
     void setVisitedLinkTextStrokeColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextStrokeColor, v); }
@@ -1710,10 +1700,8 @@
     Color visitedLinkBorderTopColor() const { return rareNonInheritedData->m_visitedLinkBorderTopColor; }
     Color visitedLinkOutlineColor() const { return rareNonInheritedData->m_visitedLinkOutlineColor; }
     Color visitedLinkColumnRuleColor() const { return rareNonInheritedData->m_multiCol->m_visitedLinkColumnRuleColor; }
-#if ENABLE(CSS3_TEXT)
     Color textDecorationColor() const { return rareNonInheritedData->m_textDecorationColor; }
     Color visitedLinkTextDecorationColor() const { return rareNonInheritedData->m_visitedLinkTextDecorationColor; }
-#endif // CSS3_TEXT
     Color visitedLinkTextEmphasisColor() const { return rareInheritedData->visitedLinkTextEmphasisColor; }
     Color visitedLinkTextFillColor() const { return rareInheritedData->visitedLinkTextFillColor; }
     Color visitedLinkTextStrokeColor() const { return rareInheritedData->visitedLinkTextStrokeColor; }
diff --git a/Source/core/rendering/style/RenderStyleConstants.h b/Source/core/rendering/style/RenderStyleConstants.h
index f929072..d21c15f 100644
--- a/Source/core/rendering/style/RenderStyleConstants.h
+++ b/Source/core/rendering/style/RenderStyleConstants.h
@@ -35,18 +35,20 @@
 };
 
 // The difference between two styles.  The following values are used:
-// (1) StyleDifferenceEqual - The two styles are identical
-// (2) StyleDifferenceRecompositeLayer - The layer needs its position and transform updated, but no repaint
+// (1) StyleDifferenceEqual - The two styles are identical.
+// (2) StyleDifferenceRecompositeLayer - The layer needs its position and transform updated, but no repaint.
 // (3) StyleDifferenceRepaint - The object just needs to be repainted.
-// (4) StyleDifferenceRepaintLayer - The layer and its descendant layers needs to be repainted.
-// (5) StyleDifferenceLayoutPositionedMovementOnly - Only the position of this positioned object has been updated
-// (6) StyleDifferenceSimplifiedLayout - Only overflow needs to be recomputed
-// (7) StyleDifferenceSimplifiedLayoutAndPositionedMovement - Both positioned movement and simplified layout updates are required.
-// (8) StyleDifferenceLayout - A full layout is required.
+// (4) StyleDifferenceRepaintIfText - The object needs to be repainted if it contains text.
+// (5) StyleDifferenceRepaintLayer - The layer and its descendant layers needs to be repainted.
+// (6) StyleDifferenceLayoutPositionedMovementOnly - Only the position of this positioned object has been updated.
+// (7) StyleDifferenceSimplifiedLayout - Only overflow needs to be recomputed.
+// (8) StyleDifferenceSimplifiedLayoutAndPositionedMovement - Both positioned movement and simplified layout updates are required.
+// (9) StyleDifferenceLayout - A full layout is required.
 enum StyleDifference {
     StyleDifferenceEqual,
     StyleDifferenceRecompositeLayer,
     StyleDifferenceRepaint,
+    StyleDifferenceRepaintIfText,
     StyleDifferenceRepaintLayer,
     StyleDifferenceLayoutPositionedMovementOnly,
     StyleDifferenceSimplifiedLayout,
@@ -117,7 +119,7 @@
 // Random visual rendering model attributes. Not inherited.
 
 enum EOverflow {
-    OVISIBLE, OHIDDEN, OSCROLL, OAUTO, OOVERLAY, OMARQUEE, OPAGEDX, OPAGEDY
+    OVISIBLE, OHIDDEN, OSCROLL, OAUTO, OOVERLAY, OPAGEDX, OPAGEDY
 };
 
 enum EVerticalAlign {
@@ -344,12 +346,10 @@
 
 enum TextDecorationStyle {
     TextDecorationStyleSolid,
-#if ENABLE(CSS3_TEXT)
     TextDecorationStyleDouble,
     TextDecorationStyleDotted,
     TextDecorationStyleDashed,
     TextDecorationStyleWavy
-#endif // CSS3_TEXT
 };
 
 #if ENABLE(CSS3_TEXT)
diff --git a/Source/core/rendering/style/StylePendingShader.h b/Source/core/rendering/style/StylePendingShader.h
index c29de55..a97c66a 100644
--- a/Source/core/rendering/style/StylePendingShader.h
+++ b/Source/core/rendering/style/StylePendingShader.h
@@ -30,8 +30,8 @@
 #ifndef StylePendingShader_h
 #define StylePendingShader_h
 
+#include "core/css/CSSShaderValue.h"
 #include "core/css/CSSValue.h"
-#include "core/css/WebKitCSSShaderValue.h"
 #include "core/rendering/style/StyleShader.h"
 #include <wtf/PassRefPtr.h>
 
@@ -41,18 +41,18 @@
 
 class StylePendingShader : public StyleShader {
 public:
-    static PassRefPtr<StylePendingShader> create(WebKitCSSShaderValue* value) { return adoptRef(new StylePendingShader(value)); }
+    static PassRefPtr<StylePendingShader> create(CSSShaderValue* value) { return adoptRef(new StylePendingShader(value)); }
     
     virtual PassRefPtr<CSSValue> cssValue() const { return m_value; }
-    WebKitCSSShaderValue* cssShaderValue() const { return m_value; }
+    CSSShaderValue* cssShaderValue() const { return m_value; }
 private:
-    StylePendingShader(WebKitCSSShaderValue* value)
+    StylePendingShader(CSSShaderValue* value)
         : m_value(value)
     {
          m_isPendingShader = true;
     }
     
-    WebKitCSSShaderValue* m_value; // Not retained; it owns us.
+    CSSShaderValue* m_value; // Not retained; it owns us.
 };
 
 }
diff --git a/Source/core/rendering/style/StyleRareInheritedData.cpp b/Source/core/rendering/style/StyleRareInheritedData.cpp
index 0f31382..bae67da 100644
--- a/Source/core/rendering/style/StyleRareInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareInheritedData.cpp
@@ -71,7 +71,6 @@
     , lineBreak(LineBreakAuto)
     , resize(RenderStyle::initialResize())
     , userSelect(RenderStyle::initialUserSelect())
-    , colorSpace(ColorSpaceDeviceRGB)
     , speak(SpeakNormal)
     , hyphens(HyphensManual)
     , textEmphasisFill(TextEmphasisFillFilled)
@@ -129,7 +128,6 @@
     , lineBreak(o.lineBreak)
     , resize(o.resize)
     , userSelect(o.userSelect)
-    , colorSpace(o.colorSpace)
     , speak(o.speak)
     , hyphens(o.hyphens)
     , textEmphasisFill(o.textEmphasisFill)
@@ -206,7 +204,6 @@
 #endif
         && resize == o.resize
         && userSelect == o.userSelect
-        && colorSpace == o.colorSpace
         && speak == o.speak
         && hyphens == o.hyphens
         && hyphenationLimitBefore == o.hyphenationLimitBefore
diff --git a/Source/core/rendering/style/StyleRareInheritedData.h b/Source/core/rendering/style/StyleRareInheritedData.h
index 0ffd6af..2bbeb28 100644
--- a/Source/core/rendering/style/StyleRareInheritedData.h
+++ b/Source/core/rendering/style/StyleRareInheritedData.h
@@ -65,14 +65,14 @@
     float textStrokeWidth;
     Color textFillColor;
     Color textEmphasisColor;
-    
+
     Color visitedLinkTextStrokeColor;
     Color visitedLinkTextFillColor;
-    Color visitedLinkTextEmphasisColor;    
+    Color visitedLinkTextEmphasisColor;
 
     OwnPtr<ShadowData> textShadow; // Our text shadow information for shadowed text drawing.
     AtomicString highlight; // Apple-specific extension for custom highlight rendering.
-    
+
     RefPtr<CursorList> cursorData;
     Length indent;
     float m_effectiveZoom;
@@ -82,7 +82,7 @@
     short orphans;
     unsigned m_hasAutoWidows : 1;
     unsigned m_hasAutoOrphans : 1;
-    
+
     unsigned textSecurity : 2; // ETextSecurity
     unsigned userModify : 2; // EUserModify (editing)
     unsigned wordBreak : 2; // EWordBreak
@@ -90,7 +90,6 @@
     unsigned lineBreak : 3; // LineBreak
     unsigned resize : 2; // EResize
     unsigned userSelect : 2; // EUserSelect
-    unsigned colorSpace : 1; // ColorSpace
     unsigned speak : 3; // ESpeak
     unsigned hyphens : 2; // Hyphens
     unsigned textEmphasisFill : 1; // TextEmphasisFill
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.cpp b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
index b54b0ea..b894899 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
@@ -72,9 +72,7 @@
     , m_appearance(RenderStyle::initialAppearance())
     , m_borderFit(RenderStyle::initialBorderFit())
     , m_textCombine(RenderStyle::initialTextCombine())
-#if ENABLE(CSS3_TEXT)
     , m_textDecorationStyle(RenderStyle::initialTextDecorationStyle())
-#endif // CSS3_TEXT
     , m_wrapFlow(RenderStyle::initialWrapFlow())
     , m_wrapThrough(RenderStyle::initialWrapThrough())
     , m_runningAcceleratedAnimation(false)
@@ -117,10 +115,8 @@
     , m_shapeMargin(o.m_shapeMargin)
     , m_shapePadding(o.m_shapePadding)
     , m_clipPath(o.m_clipPath)
-#if ENABLE(CSS3_TEXT)
     , m_textDecorationColor(o.m_textDecorationColor)
     , m_visitedLinkTextDecorationColor(o.m_visitedLinkTextDecorationColor)
-#endif // CSS3_TEXT
     , m_visitedLinkBackgroundColor(o.m_visitedLinkBackgroundColor)
     , m_visitedLinkOutlineColor(o.m_visitedLinkOutlineColor)
     , m_visitedLinkBorderLeftColor(o.m_visitedLinkBorderLeftColor)
@@ -148,9 +144,7 @@
     , m_appearance(o.m_appearance)
     , m_borderFit(o.m_borderFit)
     , m_textCombine(o.m_textCombine)
-#if ENABLE(CSS3_TEXT)
     , m_textDecorationStyle(o.m_textDecorationStyle)
-#endif // CSS3_TEXT
     , m_wrapFlow(o.m_wrapFlow)
     , m_wrapThrough(o.m_wrapThrough)
     , m_runningAcceleratedAnimation(o.m_runningAcceleratedAnimation)
@@ -196,10 +190,8 @@
         && m_shapeMargin == o.m_shapeMargin
         && m_shapePadding == o.m_shapePadding
         && m_clipPath == o.m_clipPath
-#if ENABLE(CSS3_TEXT)
         && m_textDecorationColor == o.m_textDecorationColor
         && m_visitedLinkTextDecorationColor == o.m_visitedLinkTextDecorationColor
-#endif // CSS3_TEXT
         && m_visitedLinkBackgroundColor == o.m_visitedLinkBackgroundColor
         && m_visitedLinkOutlineColor == o.m_visitedLinkOutlineColor
         && m_visitedLinkBorderLeftColor == o.m_visitedLinkBorderLeftColor
@@ -227,9 +219,7 @@
         && m_appearance == o.m_appearance
         && m_borderFit == o.m_borderFit
         && m_textCombine == o.m_textCombine
-#if ENABLE(CSS3_TEXT)
         && m_textDecorationStyle == o.m_textDecorationStyle
-#endif // CSS3_TEXT
         && m_wrapFlow == o.m_wrapFlow
         && m_wrapThrough == o.m_wrapThrough
         && !m_runningAcceleratedAnimation && !o.m_runningAcceleratedAnimation
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.h b/Source/core/rendering/style/StyleRareNonInheritedData.h
index c715d0d..15ab8f9 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.h
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.h
@@ -132,10 +132,8 @@
 
     RefPtr<ClipPathOperation> m_clipPath;
 
-#if ENABLE(CSS3_TEXT)
     Color m_textDecorationColor;
     Color m_visitedLinkTextDecorationColor;
-#endif // CSS3_TEXT
     Color m_visitedLinkBackgroundColor;
     Color m_visitedLinkOutlineColor;
     Color m_visitedLinkBorderLeftColor;
@@ -170,9 +168,7 @@
     unsigned m_borderFit : 1; // EBorderFit
     unsigned m_textCombine : 1; // CSS3 text-combine properties
 
-#if ENABLE(CSS3_TEXT)
     unsigned m_textDecorationStyle : 3; // TextDecorationStyle
-#endif // CSS3_TEXT
     unsigned m_wrapFlow: 3; // WrapFlow
     unsigned m_wrapThrough: 1; // WrapThrough
 
diff --git a/Source/core/rendering/svg/RenderSVGContainer.cpp b/Source/core/rendering/svg/RenderSVGContainer.cpp
index 1ff86de..25e5356 100644
--- a/Source/core/rendering/svg/RenderSVGContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGContainer.cpp
@@ -105,6 +105,8 @@
 
 void RenderSVGContainer::paint(PaintInfo& paintInfo, const LayoutPoint&)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     if (paintInfo.context->paintingDisabled())
         return;
 
diff --git a/Source/core/rendering/svg/RenderSVGImage.cpp b/Source/core/rendering/svg/RenderSVGImage.cpp
index 599955f..5edf820 100644
--- a/Source/core/rendering/svg/RenderSVGImage.cpp
+++ b/Source/core/rendering/svg/RenderSVGImage.cpp
@@ -125,6 +125,8 @@
 
 void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint&)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     if (paintInfo.context->paintingDisabled() || style()->visibility() == HIDDEN || !m_imageResource->hasImage())
         return;
 
@@ -167,7 +169,7 @@
     if (style()->svgStyle()->bufferedRendering() != BR_STATIC)
         useLowQualityScaling = ImageQualityController::imageQualityController()->shouldPaintAtLowQuality(paintInfo.context, this, image.get(), image.get(), LayoutSize(destRect.size()));
 
-    paintInfo.context->drawImage(image.get(), style()->colorSpace(), destRect, srcRect, CompositeSourceOver, DoNotRespectImageOrientation, useLowQualityScaling);
+    paintInfo.context->drawImage(image.get(), destRect, srcRect, CompositeSourceOver, DoNotRespectImageOrientation, useLowQualityScaling);
 }
 
 void RenderSVGImage::invalidateBufferedForeground()
diff --git a/Source/core/rendering/svg/RenderSVGInlineText.cpp b/Source/core/rendering/svg/RenderSVGInlineText.cpp
index 8a11eab..6b620aa 100644
--- a/Source/core/rendering/svg/RenderSVGInlineText.cpp
+++ b/Source/core/rendering/svg/RenderSVGInlineText.cpp
@@ -26,6 +26,7 @@
 #include "core/rendering/svg/RenderSVGInlineText.h"
 
 #include "core/css/CSSFontSelector.h"
+#include "core/css/FontSize.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/editing/VisiblePosition.h"
 #include "core/rendering/svg/RenderSVGText.h"
@@ -235,7 +236,7 @@
     FontDescription fontDescription(style->fontDescription());
 
     // FIXME: We need to better handle the case when we compute very small fonts below (below 1pt).
-    fontDescription.setComputedSize(StyleResolver::getComputedSizeFromSpecifiedSize(document, scalingFactor, fontDescription.isAbsoluteSize(), fontDescription.computedSize(), DoNotUseSmartMinimumForFontSize));
+    fontDescription.setComputedSize(FontSize::getComputedSizeFromSpecifiedSize(document, scalingFactor, fontDescription.isAbsoluteSize(), fontDescription.computedSize(), DoNotUseSmartMinimumForFontSize));
 
     scaledFont = Font(fontDescription, 0, 0);
     scaledFont.update(styleResolver->fontSelector());
diff --git a/Source/core/rendering/svg/RenderSVGPath.cpp b/Source/core/rendering/svg/RenderSVGPath.cpp
index ccc7ea9..ce8b421 100644
--- a/Source/core/rendering/svg/RenderSVGPath.cpp
+++ b/Source/core/rendering/svg/RenderSVGPath.cpp
@@ -72,7 +72,7 @@
     else if (Pattern* pattern = context->strokePattern())
         context->setFillPattern(pattern);
     else
-        context->setFillColor(context->strokeColor(), context->strokeColorSpace());
+        context->setFillColor(context->strokeColor());
 }
 
 void RenderSVGPath::strokeShape(GraphicsContext* context) const
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
index 58d1dd7..f2c6834 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
@@ -155,7 +155,7 @@
     SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(object, absoluteTransform);
 
     if (shouldCreateClipData && !repaintRect.isEmpty()) {
-        if (!SVGRenderingContext::createImageBuffer(repaintRect, absoluteTransform, clipperData->clipMaskImage, ColorSpaceDeviceRGB, Unaccelerated))
+        if (!SVGRenderingContext::createImageBuffer(repaintRect, absoluteTransform, clipperData->clipMaskImage, Unaccelerated))
             return false;
 
         GraphicsContext* maskContext = clipperData->clipMaskImage->context();
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
index 02bae26..3c28875 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
@@ -88,7 +88,7 @@
             continue;
 
         SVGElement* element = toSVGElement(node);
-        if (!element->isFilterEffect())
+        if (!element->isFilterEffect() || !element->renderer())
             continue;
 
         SVGFilterPrimitiveStandardAttributes* effectElement = static_cast<SVGFilterPrimitiveStandardAttributes*>(element);
@@ -215,7 +215,7 @@
 
     OwnPtr<ImageBuffer> sourceGraphic;
     RenderingMode renderingMode = object->document()->page()->settings()->acceleratedFiltersEnabled() ? Accelerated : Unaccelerated;
-    if (!SVGRenderingContext::createImageBuffer(filterData->drawingRegion, effectiveTransform, sourceGraphic, ColorSpaceLinearRGB, renderingMode)) {
+    if (!SVGRenderingContext::createImageBuffer(filterData->drawingRegion, effectiveTransform, sourceGraphic, renderingMode)) {
         ASSERT(!m_filter.contains(object));
         filterData->savedContext = context;
         m_filter.set(object, filterData.leakPtr());
@@ -299,7 +299,7 @@
             context->concatCTM(filterData->shearFreeAbsoluteTransform.inverse());
 
             context->scale(FloatSize(1 / filterData->filter->filterResolution().width(), 1 / filterData->filter->filterResolution().height()));
-            context->drawImageBuffer(resultImage, object->style()->colorSpace(), lastEffect->absolutePaintRect());
+            context->drawImageBuffer(resultImage, lastEffect->absolutePaintRect());
             context->scale(filterData->filter->filterResolution());
 
             context->concatCTM(filterData->shearFreeAbsoluteTransform);
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
index 39bd010..de18fe9 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
@@ -99,7 +99,7 @@
         const SVGRenderStyle* svgStyle = style()->svgStyle();
         ASSERT(svgStyle);
         ColorSpace colorSpace = svgStyle->colorInterpolation() == CI_LINEARRGB ? ColorSpaceLinearRGB : ColorSpaceDeviceRGB;
-        if (!SVGRenderingContext::createImageBuffer(repaintRect, absoluteTransform, maskerData->maskImage, colorSpace, Unaccelerated))
+        if (!SVGRenderingContext::createImageBuffer(repaintRect, absoluteTransform, maskerData->maskImage, Unaccelerated))
             return false;
 
         if (!drawContentIntoMaskImage(maskerData, colorSpace, maskElement, object)) {
diff --git a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
index ecd8a90..d496544 100644
--- a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
@@ -241,7 +241,7 @@
 
     OwnPtr<ImageBuffer> tileImage;
 
-    if (!SVGRenderingContext::createImageBufferForPattern(absoluteTileBoundaries, clampedAbsoluteTileBoundaries, tileImage, ColorSpaceDeviceRGB, Unaccelerated))
+    if (!SVGRenderingContext::createImageBufferForPattern(absoluteTileBoundaries, clampedAbsoluteTileBoundaries, tileImage, Unaccelerated))
         return nullptr;
 
     GraphicsContext* tileImageContext = tileImage->context();
diff --git a/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp b/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp
index 884da10..5693fb1 100644
--- a/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp
@@ -49,7 +49,6 @@
     ASSERT(resourceMode != ApplyToDefaultMode);
 
     const SVGRenderStyle* svgStyle = style ? style->svgStyle() : 0;
-    ColorSpace colorSpace = style ? style->colorSpace() : ColorSpaceDeviceRGB;
 
     bool isRenderingMask = false;
     if (object->frame() && object->frame()->view())
@@ -60,7 +59,7 @@
             context->setAlpha(svgStyle->fillOpacity());
         else
             context->setAlpha(1);
-        context->setFillColor(m_color, colorSpace);
+        context->setFillColor(m_color);
         if (!isRenderingMask)
             context->setFillRule(svgStyle ? svgStyle->fillRule() : RULE_NONZERO);
 
@@ -70,7 +69,7 @@
         // When rendering the mask for a RenderSVGResourceClipper, the stroke code path is never hit.
         ASSERT(!isRenderingMask);
         context->setAlpha(svgStyle ? svgStyle->strokeOpacity() : 1);
-        context->setStrokeColor(m_color, colorSpace);
+        context->setStrokeColor(m_color);
 
         if (style)
             SVGRenderSupport::applyStrokeStyleToContext(context, style, object);
diff --git a/Source/core/rendering/svg/RenderSVGRoot.cpp b/Source/core/rendering/svg/RenderSVGRoot.cpp
index 32ffe2d..15b4704 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.cpp
+++ b/Source/core/rendering/svg/RenderSVGRoot.cpp
@@ -248,6 +248,8 @@
         m_needsBoundariesOrTransformUpdate = false;
     }
 
+    updateLayerTransform();
+
     repainter.repaintAfterLayout();
 
     setNeedsLayout(false);
diff --git a/Source/core/rendering/svg/RenderSVGShape.cpp b/Source/core/rendering/svg/RenderSVGShape.cpp
index 70107a8..da3574c 100644
--- a/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -265,6 +265,8 @@
 
 void RenderSVGShape::paint(PaintInfo& paintInfo, const LayoutPoint&)
 {
+    ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
+
     if (paintInfo.context->paintingDisabled() || style()->visibility() == HIDDEN || isEmpty())
         return;
     FloatRect boundingBox = repaintRectInLocalCoordinates();
diff --git a/Source/core/rendering/svg/SVGInlineTextBox.cpp b/Source/core/rendering/svg/SVGInlineTextBox.cpp
index e700ac2..3206298 100644
--- a/Source/core/rendering/svg/SVGInlineTextBox.cpp
+++ b/Source/core/rendering/svg/SVGInlineTextBox.cpp
@@ -25,6 +25,7 @@
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/platform/FloatConversion.h"
+#include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/HitTestResult.h"
@@ -244,8 +245,8 @@
         if (!fragmentTransform.isIdentity())
             paintInfo.context->concatCTM(fragmentTransform);
 
-        paintInfo.context->setFillColor(backgroundColor, style->colorSpace());
-        paintInfo.context->fillRect(selectionRectForTextFragment(fragment, fragmentStartPosition, fragmentEndPosition, style), backgroundColor, style->colorSpace());
+        paintInfo.context->setFillColor(backgroundColor);
+        paintInfo.context->fillRect(selectionRectForTextFragment(fragment, fragmentStartPosition, fragmentEndPosition, style), backgroundColor);
 
         m_paintingResourceMode = ApplyToDefaultMode;
     }
@@ -598,6 +599,7 @@
 
     const Font& scaledFont = textRenderer->scaledFont();
     const ShadowData* shadow = style->textShadow();
+    bool hasShadow = shadow;
 
     FloatPoint textOrigin(fragment.x, fragment.y);
     FloatSize textSize(fragment.width, fragment.height);
@@ -605,41 +607,34 @@
     if (scalingFactor != 1) {
         textOrigin.scale(scalingFactor, scalingFactor);
         textSize.scale(scalingFactor);
-    }
-
-    FloatRect shadowRect(FloatPoint(textOrigin.x(), textOrigin.y() - scaledFont.fontMetrics().floatAscent()), textSize);
-    TextRunPaintInfo textRunPaintInfo(textRun);
-    textRunPaintInfo.from = startPosition;
-    textRunPaintInfo.to = endPosition;
-    textRunPaintInfo.bounds = FloatRect(textOrigin, textSize);
-
-    do {
-        if (!prepareGraphicsContextForTextPainting(context, scalingFactor, textRun, style))
-            break;
-
-        FloatSize extraOffset;
-        if (shadow)
-            extraOffset = applyShadowToGraphicsContext(context, shadow, shadowRect, false /* stroked */, true /* opaque */, true /* horizontal */);
-
         context->save();
         context->scale(FloatSize(1 / scalingFactor, 1 / scalingFactor));
+    }
 
-        scaledFont.drawText(context, textRunPaintInfo, textOrigin + extraOffset);
+    if (hasShadow) {
+        DrawLooper drawLooper;
+        do {
+            FloatSize offset(shadow->x(), shadow->y());
+            drawLooper.addShadow(offset, shadow->blur(), shadow->color(),
+                DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowRespectsAlpha);
+        } while ((shadow = shadow->next()));
+        drawLooper.addUnmodifiedContent();
+        context->setDrawLooper(drawLooper);
+    }
 
-        context->restore();
-
+    if (prepareGraphicsContextForTextPainting(context, scalingFactor, textRun, style)) {
+        TextRunPaintInfo textRunPaintInfo(textRun);
+        textRunPaintInfo.from = startPosition;
+        textRunPaintInfo.to = endPosition;
+        textRunPaintInfo.bounds = FloatRect(textOrigin, textSize);
+        scaledFont.drawText(context, textRunPaintInfo, textOrigin);
         restoreGraphicsContextAfterTextPainting(context, textRun);
+    }
 
-        if (!shadow)
-            break;
-
-        if (shadow->next())
-            context->restore();
-        else
-            context->clearShadow();
-
-        shadow = shadow->next();
-    } while (shadow);
+    if (scalingFactor != 1)
+        context->restore();
+    else if (hasShadow)
+        context->clearShadow();
 }
 
 void SVGInlineTextBox::paintText(GraphicsContext* context, RenderStyle* style, RenderStyle* selectionStyle, const SVGTextFragment& fragment, bool hasSelection, bool paintSelectedTextOnly)
diff --git a/Source/core/rendering/svg/SVGRenderingContext.cpp b/Source/core/rendering/svg/SVGRenderingContext.cpp
index 53ee573..e4d7be5 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.cpp
+++ b/Source/core/rendering/svg/SVGRenderingContext.cpp
@@ -212,7 +212,7 @@
     }
 }
 
-bool SVGRenderingContext::createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform, OwnPtr<ImageBuffer>& imageBuffer, ColorSpace colorSpace, RenderingMode renderingMode)
+bool SVGRenderingContext::createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform, OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
 {
     IntRect paintRect = calculateImageBufferRect(targetRect, absoluteTransform);
     // Don't create empty ImageBuffers.
@@ -220,7 +220,7 @@
         return false;
 
     IntSize clampedSize = clampedAbsoluteSize(paintRect.size());
-    OwnPtr<ImageBuffer> image = ImageBuffer::create(clampedSize, 1, colorSpace, renderingMode);
+    OwnPtr<ImageBuffer> image = ImageBuffer::create(clampedSize, 1, renderingMode);
     if (!image)
         return false;
 
@@ -236,7 +236,7 @@
     return true;
 }
 
-bool SVGRenderingContext::createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>& imageBuffer, ColorSpace colorSpace, RenderingMode renderingMode)
+bool SVGRenderingContext::createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
 {
     IntSize imageSize(roundedIntSize(clampedAbsoluteTargetRect.size()));
     IntSize unclampedImageSize(roundedIntSize(absoluteTargetRect.size()));
@@ -245,7 +245,7 @@
     if (imageSize.isEmpty())
         return false;
 
-    OwnPtr<ImageBuffer> image = ImageBuffer::create(imageSize, 1, colorSpace, renderingMode);
+    OwnPtr<ImageBuffer> image = ImageBuffer::create(imageSize, 1, renderingMode);
     if (!image)
         return false;
 
@@ -343,7 +343,7 @@
             return false;
     }
 
-    m_paintInfo->context->drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, boundingBox);
+    m_paintInfo->context->drawImageBuffer(imageBuffer.get(), boundingBox);
     return true;
 }
 
diff --git a/Source/core/rendering/svg/SVGRenderingContext.h b/Source/core/rendering/svg/SVGRenderingContext.h
index ca72305..254aad8 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.h
+++ b/Source/core/rendering/svg/SVGRenderingContext.h
@@ -70,9 +70,9 @@
     void prepareToRenderSVGContent(RenderObject*, PaintInfo&, NeedsGraphicsContextSave = DontSaveGraphicsContext);
     bool isRenderingPrepared() const { return m_renderingFlags & RenderingPrepared; }
 
-    static bool createImageBuffer(const FloatRect& paintRect, const AffineTransform& absoluteTransform, OwnPtr<ImageBuffer>&, ColorSpace, RenderingMode);
+    static bool createImageBuffer(const FloatRect& paintRect, const AffineTransform& absoluteTransform, OwnPtr<ImageBuffer>&, RenderingMode);
     // Patterns need a different float-to-integer coordinate mapping.
-    static bool createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>&, ColorSpace, RenderingMode);
+    static bool createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>&, RenderingMode);
 
     static void renderSubtreeToImageBuffer(ImageBuffer*, RenderObject*, const AffineTransform&);
     static void clipToImageBuffer(GraphicsContext*, const AffineTransform& absoluteTransform, const FloatRect& targetRect, OwnPtr<ImageBuffer>&, bool safeToClear);
diff --git a/Source/core/rendering/svg/SVGResourcesCache.cpp b/Source/core/rendering/svg/SVGResourcesCache.cpp
index 7e002ac..bffef97 100644
--- a/Source/core/rendering/svg/SVGResourcesCache.cpp
+++ b/Source/core/rendering/svg/SVGResourcesCache.cpp
@@ -127,7 +127,7 @@
         return;
 
     // In this case the proper SVGFE*Element will decide whether the modified CSS properties require a relayout or repaint.
-    if (renderer->isSVGResourceFilterPrimitive() && diff == StyleDifferenceRepaint)
+    if (renderer->isSVGResourceFilterPrimitive() && (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintIfText))
         return;
 
     // Dynamic changes of CSS properties like 'clip-path' may require us to recompute the associated resources for a renderer.