Merge from Chromium at DEPS revision r216972

This commit was generated by merge_to_master.py.

Change-Id: Ie5904a921ece9c5959b52c8e0b74db09fa08f144
diff --git a/Source/core/Init.cpp b/Source/core/Init.cpp
index fb9a586..8aee439 100644
--- a/Source/core/Init.cpp
+++ b/Source/core/Init.cpp
@@ -53,6 +53,8 @@
         return;
     isInited = true;
 
+    // It would make logical sense to do this and WTF::StringStatics::init() in
+    // WTF::initialize() but there are ordering dependencies.
     AtomicString::init();
     HTMLNames::init();
     SVGNames::init();
diff --git a/Source/core/OWNERS b/Source/core/OWNERS
index 3e99180..a774153 100644
--- a/Source/core/OWNERS
+++ b/Source/core/OWNERS
@@ -4,7 +4,6 @@
 apavlov@chromium.org
 arv@chromium.org
 ch.dumez@sisa.samsung.com
-crogers@google.com
 darin@chromium.org
 dglazkov@chromium.org
 dimich@chromium.org
diff --git a/Source/core/accessibility/AXObjectCache.cpp b/Source/core/accessibility/AXObjectCache.cpp
index 46538b8..cea4bcd 100644
--- a/Source/core/accessibility/AXObjectCache.cpp
+++ b/Source/core/accessibility/AXObjectCache.cpp
@@ -155,7 +155,7 @@
         return 0;
 
     // get the focused node in the page
-    Document* focusedDocument = page->focusController()->focusedOrMainFrame()->document();
+    Document* focusedDocument = page->focusController().focusedOrMainFrame()->document();
     Node* focusedNode = focusedDocument->focusedElement();
     if (!focusedNode)
         focusedNode = focusedDocument;
diff --git a/Source/core/accessibility/AccessibilityMediaControls.cpp b/Source/core/accessibility/AccessibilityMediaControls.cpp
index db790ee..cf694b9 100644
--- a/Source/core/accessibility/AccessibilityMediaControls.cpp
+++ b/Source/core/accessibility/AccessibilityMediaControls.cpp
@@ -75,35 +75,35 @@
 {
     switch (controlType()) {
     case MediaEnterFullscreenButton:
-        return ASCIILiteral("EnterFullscreenButton");
+        return "EnterFullscreenButton";
     case MediaExitFullscreenButton:
-        return ASCIILiteral("ExitFullscreenButton");
+        return "ExitFullscreenButton";
     case MediaMuteButton:
-        return ASCIILiteral("MuteButton");
+        return "MuteButton";
     case MediaPlayButton:
-        return ASCIILiteral("PlayButton");
+        return "PlayButton";
     case MediaSeekBackButton:
-        return ASCIILiteral("SeekBackButton");
+        return "SeekBackButton";
     case MediaSeekForwardButton:
-        return ASCIILiteral("SeekForwardButton");
+        return "SeekForwardButton";
     case MediaRewindButton:
-        return ASCIILiteral("RewindButton");
+        return "RewindButton";
     case MediaReturnToRealtimeButton:
-        return ASCIILiteral("ReturnToRealtimeButton");
+        return "ReturnToRealtimeButton";
     case MediaUnMuteButton:
-        return ASCIILiteral("UnMuteButton");
+        return "UnMuteButton";
     case MediaPauseButton:
-        return ASCIILiteral("PauseButton");
+        return "PauseButton";
     case MediaStatusDisplay:
-        return ASCIILiteral("StatusDisplay");
+        return "StatusDisplay";
     case MediaCurrentTimeDisplay:
-        return ASCIILiteral("CurrentTimeDisplay");
+        return "CurrentTimeDisplay";
     case MediaTimeRemainingDisplay:
-        return ASCIILiteral("TimeRemainingDisplay");
+        return "TimeRemainingDisplay";
     case MediaShowClosedCaptionsButton:
-        return ASCIILiteral("ShowClosedCaptionsButton");
+        return "ShowClosedCaptionsButton";
     case MediaHideClosedCaptionsButton:
-        return ASCIILiteral("HideClosedCaptionsButton");
+        return "HideClosedCaptionsButton";
 
     default:
         break;
@@ -131,7 +131,7 @@
 String AccessibilityMediaControl::title() const
 {
     if (controlType() == MediaControlsPanel)
-        return localizedMediaControlElementString(ASCIILiteral("ControlsPanel"));
+        return localizedMediaControlElementString("ControlsPanel");
 
     return AccessibilityRenderObject::title();
 }
@@ -222,8 +222,8 @@
 const String AccessibilityMediaControlsContainer::elementTypeName() const
 {
     if (controllingVideoElement())
-        return ASCIILiteral("VideoElement");
-    return ASCIILiteral("AudioElement");
+        return "VideoElement";
+    return "AudioElement";
 }
 
 bool AccessibilityMediaControlsContainer::computeAccessibilityIsIgnored() const
@@ -255,7 +255,7 @@
 
 String AccessibilityMediaTimeline::helpText() const
 {
-    return localizedMediaControlElementHelpText(ASCIILiteral("Slider"));
+    return localizedMediaControlElementHelpText("Slider");
 }
 
 
@@ -286,9 +286,9 @@
 String AccessibilityMediaTimeDisplay::accessibilityDescription() const
 {
     if (controlType() == MediaCurrentTimeDisplay)
-        return localizedMediaControlElementString(ASCIILiteral("CurrentTimeDisplay"));
+        return localizedMediaControlElementString("CurrentTimeDisplay");
 
-    return localizedMediaControlElementString(ASCIILiteral("TimeRemainingDisplay"));
+    return localizedMediaControlElementString("TimeRemainingDisplay");
 }
 
 String AccessibilityMediaTimeDisplay::stringValue() const
diff --git a/Source/core/accessibility/AccessibilityRenderObject.cpp b/Source/core/accessibility/AccessibilityRenderObject.cpp
index a2209eb..8c32759 100644
--- a/Source/core/accessibility/AccessibilityRenderObject.cpp
+++ b/Source/core/accessibility/AccessibilityRenderObject.cpp
@@ -2212,7 +2212,7 @@
     if (!m_renderer || !m_renderer->isRenderImage())
         return 0;
 
-    CachedImage* cachedImage = toRenderImage(m_renderer)->cachedImage();
+    ImageResource* cachedImage = toRenderImage(m_renderer)->cachedImage();
     if (!cachedImage)
         return 0;
 
diff --git a/Source/core/animation/AnimatableNeutral.h b/Source/core/animation/AnimatableNeutral.h
index 757acb9..af45451 100644
--- a/Source/core/animation/AnimatableNeutral.h
+++ b/Source/core/animation/AnimatableNeutral.h
@@ -39,12 +39,6 @@
 public:
     virtual ~AnimatableNeutral() { }
 
-    virtual PassRefPtr<CSSValue> toCSSValue() const OVERRIDE
-    {
-        ASSERT_NOT_REACHED();
-        return 0;
-    }
-
 protected:
     static PassRefPtr<AnimatableNeutral> create() { return adoptRef(new AnimatableNeutral()); }
 
diff --git a/Source/core/animation/AnimatableNeutralTest.cpp b/Source/core/animation/AnimatableNeutralTest.cpp
index 0eb0188..0746962 100644
--- a/Source/core/animation/AnimatableNeutralTest.cpp
+++ b/Source/core/animation/AnimatableNeutralTest.cpp
@@ -50,8 +50,8 @@
     RefPtr<CSSValue> cssValue = CSSArrayFunctionValue::create();
     RefPtr<AnimatableValue> animatableUnknown = AnimatableUnknown::create(cssValue);
 
-    EXPECT_EQ(cssValue, AnimatableValue::add(animatableUnknown.get(), AnimatableValue::neutralValue())->toCSSValue());
-    EXPECT_EQ(cssValue, AnimatableValue::add(AnimatableValue::neutralValue(), animatableUnknown.get())->toCSSValue());
+    EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::add(animatableUnknown.get(), AnimatableValue::neutralValue()).get())->toCSSValue());
+    EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::add(AnimatableValue::neutralValue(), animatableUnknown.get()).get())->toCSSValue());
 }
 
 }
diff --git a/Source/core/animation/AnimatableNumber.cpp b/Source/core/animation/AnimatableNumber.cpp
index c05e1a3..3693953 100644
--- a/Source/core/animation/AnimatableNumber.cpp
+++ b/Source/core/animation/AnimatableNumber.cpp
@@ -31,7 +31,9 @@
 #include "config.h"
 #include "core/animation/AnimatableNumber.h"
 
+#include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/platform/CalculationValue.h"
+#include "core/platform/Length.h"
 #include "wtf/MathExtras.h"
 
 namespace WebCore {
@@ -84,6 +86,22 @@
     return toCSSPrimitiveValue();
 }
 
+double AnimatableNumber::toDouble() const
+{
+    ASSERT(m_unitType == UnitTypeNumber);
+    return m_number;
+}
+
+Length AnimatableNumber::toLength(const RenderStyle* style, const RenderStyle* rootStyle, double zoom) const
+{
+    // Avoid creating a CSSValue in the common cases
+    if (m_unitType == UnitTypeLength)
+        return Length(m_number, Fixed);
+    if (m_unitType == UnitTypePercentage)
+        return Length(m_number, Percent);
+    return toCSSPrimitiveValue()->convertToLength<AnyConversion>(style, rootStyle, zoom);
+}
+
 PassRefPtr<AnimatableValue> AnimatableNumber::interpolateTo(const AnimatableValue* value, double fraction) const
 {
     const AnimatableNumber* number = toAnimatableNumber(value);
diff --git a/Source/core/animation/AnimatableNumber.h b/Source/core/animation/AnimatableNumber.h
index 857b855..e5d6b2c 100644
--- a/Source/core/animation/AnimatableNumber.h
+++ b/Source/core/animation/AnimatableNumber.h
@@ -67,7 +67,9 @@
     {
         return adoptRef(new AnimatableNumber(number, unitType, cssPrimitiveValue));
     }
-    virtual PassRefPtr<CSSValue> toCSSValue() const OVERRIDE;
+    PassRefPtr<CSSValue> toCSSValue() const;
+    double toDouble() const;
+    Length toLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, double zoom) const;
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
diff --git a/Source/core/animation/AnimatableNumberTest.cpp b/Source/core/animation/AnimatableNumberTest.cpp
index d11ea0a..2399d03 100644
--- a/Source/core/animation/AnimatableNumberTest.cpp
+++ b/Source/core/animation/AnimatableNumberTest.cpp
@@ -77,11 +77,11 @@
     }
     bool testInterpolate(CSSValue* cssValueExpected, AnimatableNumber* numberA, AnimatableNumber* numberB, double fraction)
     {
-        return AnimatableValue::interpolate(numberA, numberB, fraction)->toCSSValue()->equals(*cssValueExpected);
+        return toAnimatableNumber(AnimatableValue::interpolate(numberA, numberB, fraction).get())->toCSSValue()->equals(*cssValueExpected);
     }
     bool testAdd(CSSValue* cssValueExpected, AnimatableNumber* numberA, AnimatableNumber* numberB)
     {
-        return AnimatableValue::add(numberA, numberB)->toCSSValue()->equals(*cssValueExpected);
+        return toAnimatableNumber(AnimatableValue::add(numberA, numberB).get())->toCSSValue()->equals(*cssValueExpected);
     }
 };
 
diff --git a/Source/core/animation/AnimatableUnknown.h b/Source/core/animation/AnimatableUnknown.h
index 62d8d74..c136380 100644
--- a/Source/core/animation/AnimatableUnknown.h
+++ b/Source/core/animation/AnimatableUnknown.h
@@ -44,7 +44,7 @@
         return adoptRef(new AnimatableUnknown(value));
     }
 
-    virtual PassRefPtr<CSSValue> toCSSValue() const OVERRIDE { return m_value; }
+    PassRefPtr<CSSValue> toCSSValue() const { return m_value; }
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue* value, double fraction) const OVERRIDE
@@ -68,6 +68,12 @@
     const RefPtr<CSSValue> m_value;
 };
 
+inline const AnimatableUnknown* toAnimatableUnknown(const AnimatableValue* value)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(value && value->isUnknown());
+    return static_cast<const AnimatableUnknown*>(value);
+}
+
 } // namespace WebCore
 
 #endif // AnimatableUnknown_h
diff --git a/Source/core/animation/AnimatableUnknownTest.cpp b/Source/core/animation/AnimatableUnknownTest.cpp
index a5c51d9..60557e4 100644
--- a/Source/core/animation/AnimatableUnknownTest.cpp
+++ b/Source/core/animation/AnimatableUnknownTest.cpp
@@ -65,28 +65,28 @@
 
 TEST_F(AnimatableUnknownTest, ToCSSValue)
 {
-    EXPECT_EQ(cssValue, animatableUnknown->toCSSValue());
+    EXPECT_EQ(cssValue, toAnimatableUnknown(animatableUnknown.get())->toCSSValue());
 }
 
 TEST_F(AnimatableUnknownTest, Interpolate)
 {
-    EXPECT_EQ(cssValue, AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0)->toCSSValue());
-    EXPECT_EQ(cssValue, AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0.4)->toCSSValue());
-    EXPECT_EQ(otherCSSValue, AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0.5)->toCSSValue());
-    EXPECT_EQ(otherCSSValue, AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0.6)->toCSSValue());
-    EXPECT_EQ(otherCSSValue, AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 1)->toCSSValue());
+    EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0).get())->toCSSValue());
+    EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0.4).get())->toCSSValue());
+    EXPECT_EQ(otherCSSValue, toAnimatableUnknown(AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0.5).get())->toCSSValue());
+    EXPECT_EQ(otherCSSValue, toAnimatableUnknown(AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0.6).get())->toCSSValue());
+    EXPECT_EQ(otherCSSValue, toAnimatableUnknown(AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 1).get())->toCSSValue());
 
-    EXPECT_EQ(otherCSSValue, AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 0)->toCSSValue());
-    EXPECT_EQ(otherCSSValue, AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 0.4)->toCSSValue());
-    EXPECT_EQ(cssValue, AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 0.5)->toCSSValue());
-    EXPECT_EQ(cssValue, AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 0.6)->toCSSValue());
-    EXPECT_EQ(cssValue, AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 1)->toCSSValue());
+    EXPECT_EQ(otherCSSValue, toAnimatableUnknown(AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 0).get())->toCSSValue());
+    EXPECT_EQ(otherCSSValue, toAnimatableUnknown(AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 0.4).get())->toCSSValue());
+    EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 0.5).get())->toCSSValue());
+    EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 0.6).get())->toCSSValue());
+    EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 1).get())->toCSSValue());
 }
 
 TEST_F(AnimatableUnknownTest, Add)
 {
-    EXPECT_EQ(otherCSSValue, AnimatableValue::add(animatableUnknown.get(), otherAnimatableUnknown.get())->toCSSValue());
-    EXPECT_EQ(cssValue, AnimatableValue::add(otherAnimatableUnknown.get(), animatableUnknown.get())->toCSSValue());
+    EXPECT_EQ(otherCSSValue, toAnimatableUnknown(AnimatableValue::add(animatableUnknown.get(), otherAnimatableUnknown.get()).get())->toCSSValue());
+    EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::add(otherAnimatableUnknown.get(), animatableUnknown.get()).get())->toCSSValue());
 }
 
 }
diff --git a/Source/core/animation/AnimatableValue.h b/Source/core/animation/AnimatableValue.h
index 14323cf..3145e0a 100644
--- a/Source/core/animation/AnimatableValue.h
+++ b/Source/core/animation/AnimatableValue.h
@@ -41,7 +41,6 @@
 class AnimatableValue : public RefCounted<AnimatableValue> {
 public:
     virtual ~AnimatableValue() { }
-    virtual PassRefPtr<CSSValue> toCSSValue() const = 0;
 
     static const AnimatableValue* neutralValue();
 
diff --git a/Source/core/animation/AnimationEffect.h b/Source/core/animation/AnimationEffect.h
index 57b053b..89b3494 100644
--- a/Source/core/animation/AnimationEffect.h
+++ b/Source/core/animation/AnimationEffect.h
@@ -52,6 +52,7 @@
     class CompositableValue : public RefCounted<CompositableValue> {
     public:
         virtual ~CompositableValue() { }
+        virtual bool dependsOnUnderlyingValue() const = 0;
         virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue*) const = 0;
     };
 
diff --git a/Source/core/animation/KeyframeAnimationEffect.cpp b/Source/core/animation/KeyframeAnimationEffect.cpp
index cc5063c..a9cc771 100644
--- a/Source/core/animation/KeyframeAnimationEffect.cpp
+++ b/Source/core/animation/KeyframeAnimationEffect.cpp
@@ -44,6 +44,10 @@
     {
         return adoptRef(new ReplaceCompositableValue(value));
     }
+    virtual bool dependsOnUnderlyingValue() const
+    {
+        return false;
+    }
     virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const
     {
         return PassRefPtr<AnimatableValue>(m_value);
@@ -62,6 +66,10 @@
     {
         return adoptRef(new AddCompositableValue(value));
     }
+    virtual bool dependsOnUnderlyingValue() const
+    {
+        return true;
+    }
     virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const
     {
         return AnimatableValue::add(underlyingValue, m_value.get());
@@ -80,6 +88,10 @@
     {
         return adoptRef(new BlendedCompositableValue(before, after, fraction));
     }
+    virtual bool dependsOnUnderlyingValue() const
+    {
+        return m_dependsOnUnderlyingValue;
+    }
     virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const
     {
         return AnimatableValue::interpolate(m_before->compositeOnto(underlyingValue).get(), m_after->compositeOnto(underlyingValue).get(), m_fraction);
@@ -89,10 +101,12 @@
         : m_before(const_cast<AnimationEffect::CompositableValue*>(before))
         , m_after(const_cast<AnimationEffect::CompositableValue*>(after))
         , m_fraction(fraction)
+        , m_dependsOnUnderlyingValue(before->dependsOnUnderlyingValue() || after->dependsOnUnderlyingValue())
     { }
     RefPtr<AnimationEffect::CompositableValue> m_before;
     RefPtr<AnimationEffect::CompositableValue> m_after;
     double m_fraction;
+    bool m_dependsOnUnderlyingValue;
 };
 
 } // namespace
diff --git a/Source/core/animation/KeyframeAnimationEffectTest.cpp b/Source/core/animation/KeyframeAnimationEffectTest.cpp
index 0ea68cc..03787a5 100644
--- a/Source/core/animation/KeyframeAnimationEffectTest.cpp
+++ b/Source/core/animation/KeyframeAnimationEffectTest.cpp
@@ -64,7 +64,15 @@
 
 void expectDoubleValue(double expectedValue, PassRefPtr<AnimatableValue> value)
 {
-    EXPECT_FLOAT_EQ(static_cast<float>(expectedValue), toCSSPrimitiveValue(value->toCSSValue().get())->getDoubleValue());
+    ASSERT_TRUE(value->isNumber() || value->isUnknown());
+
+    double actualValue;
+    if (value->isNumber())
+        actualValue = toCSSPrimitiveValue(toAnimatableNumber(value.get())->toCSSValue().get())->getDoubleValue();
+    else
+        actualValue = toCSSPrimitiveValue(toAnimatableUnknown(value.get())->toCSSValue().get())->getDoubleValue();
+
+    EXPECT_FLOAT_EQ(static_cast<float>(expectedValue), actualValue);
 }
 
 
@@ -333,4 +341,30 @@
     expectDoubleValue(2.0, effect->sample(2, 0.5)->begin()->value->compositeOnto(unknownAnimatableValue(0.0)));
 }
 
+TEST(KeyframeAnimationEffect, DependsOnUnderlyingValue)
+{
+    KeyframeAnimationEffect::KeyframeVector keyframes(3);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
+    keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(0.5);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
+    keyframes[2] = Keyframe::create();
+    keyframes[2]->setOffset(1.0);
+    keyframes[2]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
+
+    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
+    EXPECT_TRUE(effect->sample(0, 0)->begin()->value->dependsOnUnderlyingValue());
+    EXPECT_TRUE(effect->sample(0, 0.1)->begin()->value->dependsOnUnderlyingValue());
+    EXPECT_TRUE(effect->sample(0, 0.25)->begin()->value->dependsOnUnderlyingValue());
+    EXPECT_TRUE(effect->sample(0, 0.4)->begin()->value->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 0.5)->begin()->value->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 0.6)->begin()->value->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 0.75)->begin()->value->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 0.8)->begin()->value->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 1)->begin()->value->dependsOnUnderlyingValue());
+}
+
 } // namespace
diff --git a/Source/core/animation/css/CSSAnimatableValueFactory.cpp b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
index e6c27dd..3d97ec3 100644
--- a/Source/core/animation/css/CSSAnimatableValueFactory.cpp
+++ b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
@@ -138,7 +138,7 @@
         return AnimatableNumber::create(length.value(), AnimatableNumber::UnitTypeViewportMax);
     case Calculated:
         // FIXME: Convert platform calcs to CSS calcs.
-        ASSERT_WITH_MESSAGE(false, "Unable to convert platform CalculationValue to AnimatableValue, not yet implemented!");
+        ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: Convert platform CalculationValue to AnimatableValue");
         return 0;
     case Auto:
     case Intrinsic:
@@ -214,7 +214,7 @@
     case CSSPropertyWidth:
         return createFromLength(style->width(), style);
     default:
-        ASSERT_WITH_MESSAGE(false, "Unable to create AnimatableValue from render style, not yet implemented!");
+        RELEASE_ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: Create AnimatableValue from render style");
         return 0;
     }
 }
diff --git a/Source/core/animation/css/CSSAnimations.cpp b/Source/core/animation/css/CSSAnimations.cpp
index d223c01..f3d06f2 100644
--- a/Source/core/animation/css/CSSAnimations.cpp
+++ b/Source/core/animation/css/CSSAnimations.cpp
@@ -124,6 +124,8 @@
     if (display != NONE) {
         for (size_t i = 0; animationDataList && i < animationDataList->size(); ++i) {
             const CSSAnimationData* animationData = animationDataList->animation(i);
+            if (animationData->isNoneAnimation())
+                continue;
             ASSERT(animationData->isValidAnimation());
             AtomicString animationName(animationData->name());
 
@@ -137,7 +139,7 @@
 
             // If there's a delay, no styles will apply yet.
             if (animationData->isDelaySet() && animationData->delay()) {
-                RELEASE_ASSERT_WITH_MESSAGE(animationData->delay() > 0, "Negative delay is not yet supported.");
+                RELEASE_ASSERT_WITH_MESSAGE(animationData->delay() > 0, "Web Animations not yet implemented: Negative delay");
                 continue;
             }
 
@@ -168,6 +170,8 @@
     if (style->display() != NONE) {
         for (size_t i = 0; animationDataList && i < animationDataList->size(); ++i) {
             const CSSAnimationData* animationData = animationDataList->animation(i);
+            if (animationData->isNoneAnimation())
+                continue;
             ASSERT(animationData->isValidAnimation());
             AtomicString animationName(animationData->name());
 
diff --git a/Source/core/core.gyp b/Source/core/core.gyp
index fe62d41..7bf2ad2 100644
--- a/Source/core/core.gyp
+++ b/Source/core/core.gyp
@@ -638,6 +638,12 @@
             ['exclude', 'platform/chromium/ScrollbarThemeChromiumDefault.h'],
           ],
         }],
+        ['use_default_render_theme==0 and OS!="android"', {
+          'sources/': [
+            ['exclude', 'platform/chromium/ScrollbarThemeChromiumOverlay.cpp'],
+            ['exclude', 'platform/chromium/ScrollbarThemeChromiumOverlay.h'],
+          ]
+        }],
         ['OS=="linux" or OS=="android"', {
           'sources/': [
             # Cherry-pick files excluded by the broader regular expressions above.
diff --git a/Source/core/core.gypi b/Source/core/core.gypi
index 11036e7..fba11fa 100644
--- a/Source/core/core.gypi
+++ b/Source/core/core.gypi
@@ -198,26 +198,15 @@
             'html/URL.idl',
             'html/ValidityState.idl',
             'html/canvas/ANGLEInstancedArrays.idl',
-            'html/canvas/ArrayBufferView.idl',
             'html/canvas/CanvasGradient.idl',
             'html/canvas/CanvasRenderingContext.idl',
             'html/canvas/CanvasRenderingContext2D.idl',
             'html/canvas/Canvas2DContextAttributes.idl',
-            'html/canvas/DataView.idl',
             'html/canvas/EXTTextureFilterAnisotropic.idl',
-            'html/canvas/Float32Array.idl',
-            'html/canvas/Float64Array.idl',
-            'html/canvas/Int16Array.idl',
-            'html/canvas/Int32Array.idl',
-            'html/canvas/Int8Array.idl',
             'html/canvas/OESStandardDerivatives.idl',
             'html/canvas/OESTextureHalfFloat.idl',
             'html/canvas/OESVertexArrayObject.idl',
             'html/canvas/Path.idl',
-            'html/canvas/Uint16Array.idl',
-            'html/canvas/Uint32Array.idl',
-            'html/canvas/Uint8Array.idl',
-            'html/canvas/Uint8ClampedArray.idl',
             'html/canvas/WebGLActiveInfo.idl',
             'html/canvas/WebGLCompressedTextureATC.idl',
             'html/canvas/WebGLCompressedTexturePVRTC.idl',
@@ -755,6 +744,8 @@
             'css/StyleSheetContents.h',
             'css/StyleSheetList.cpp',
             'css/StyleSheetList.h',
+            'css/resolver/AnimatedStyleBuilder.cpp',
+            'css/resolver/AnimatedStyleBuilder.h',
             'css/resolver/ElementResolveContext.cpp',
             'css/resolver/ElementResolveContext.h',
             'css/resolver/ElementStyleResources.cpp',
@@ -776,6 +767,7 @@
             'css/resolver/StyleAdjuster.cpp',
             'css/resolver/StyleAdjuster.h',
             'css/resolver/StyleBuilderCustom.cpp',
+            'css/resolver/StyleBuilderCustom.h',
             'css/resolver/StyleResolver.cpp',
             'css/resolver/StyleResolver.h',
             'css/resolver/StyleResolverState.cpp',
@@ -796,6 +788,7 @@
             'editing/Caret.cpp',
             'editing/Caret.h',
             'editing/CompositeEditCommand.cpp',
+            'editing/CompositionUnderline.h',
             'editing/CreateLinkCommand.cpp',
             'editing/CreateLinkCommand.h',
             'editing/DeleteFromTextNodeCommand.cpp',
@@ -811,6 +804,8 @@
             'editing/HTMLInterchange.cpp',
             'editing/IndentOutdentCommand.cpp',
             'editing/IndentOutdentCommand.h',
+            'editing/InputMethodController.cpp',
+            'editing/InputMethodController.h',
             'editing/InsertIntoTextNodeCommand.cpp',
             'editing/InsertIntoTextNodeCommand.h',
             'editing/InsertLineBreakCommand.cpp',
@@ -1080,7 +1075,6 @@
             'loader/ResourceLoaderOptions.h',
             'loader/SinkDocument.cpp',
             'loader/SinkDocument.h',
-            'loader/SubstituteData.cpp',
             'loader/SubstituteData.h',
             'loader/TextResourceDecoder.cpp',
             'loader/TextResourceDecoderBuilder.cpp',
@@ -1104,29 +1098,29 @@
             'loader/archive/MHTMLArchive.h',
             'loader/archive/MHTMLParser.cpp',
             'loader/archive/MHTMLParser.h',
-            'loader/cache/CachedCSSStyleSheet.cpp',
-            'loader/cache/CachedCSSStyleSheet.h',
-            'loader/cache/CachedDocument.cpp',
-            'loader/cache/CachedDocument.h',
-            'loader/cache/CachedFont.cpp',
-            'loader/cache/CachedFont.h',
-            'loader/cache/CachedImage.cpp',
-            'loader/cache/CachedRawResource.cpp',
+            'loader/cache/CSSStyleSheetResource.cpp',
+            'loader/cache/CSSStyleSheetResource.h',
+            'loader/cache/DocumentResource.cpp',
+            'loader/cache/DocumentResource.h',
+            'loader/cache/FontResource.cpp',
+            'loader/cache/FontResource.h',
+            'loader/cache/ImageResource.cpp',
+            'loader/cache/RawResource.cpp',
             'loader/cache/Resource.cpp',
             'loader/cache/ResourceClientWalker.h',
             'loader/cache/ResourcePtr.cpp',
             'loader/cache/ResourceFetcher.cpp',
             'loader/cache/FetchRequest.cpp',
             'loader/cache/FetchInitiatorInfo.h',
-            'loader/cache/CachedScript.cpp',
-            'loader/cache/CachedScript.h',
-            'loader/cache/CachedShader.cpp',
-            'loader/cache/CachedShader.h',
-            'loader/cache/CachedSVGDocumentReference.h',
-            'loader/cache/CachedTextTrack.cpp',
-            'loader/cache/CachedTextTrack.h',
-            'loader/cache/CachedXSLStyleSheet.cpp',
-            'loader/cache/CachedXSLStyleSheet.h',
+            'loader/cache/ScriptResource.cpp',
+            'loader/cache/ScriptResource.h',
+            'loader/cache/ShaderResource.cpp',
+            'loader/cache/ShaderResource.h',
+            'loader/cache/DocumentResourceReference.h',
+            'loader/cache/TextTrackResource.cpp',
+            'loader/cache/TextTrackResource.h',
+            'loader/cache/XSLStyleSheetResource.cpp',
+            'loader/cache/XSLStyleSheetResource.h',
             'loader/cache/MemoryCache.cpp',
             'page/AutoscrollController.cpp',
             'page/AutoscrollController.h',
@@ -1523,10 +1517,10 @@
             'rendering/style/ShadowData.cpp',
             'rendering/style/StyleBackgroundData.cpp',
             'rendering/style/StyleBoxData.cpp',
-            'rendering/style/StyleCachedImage.cpp',
-            'rendering/style/StyleCachedImageSet.cpp',
-            'rendering/style/StyleCachedShader.h',
-            'rendering/style/StyleCachedShader.cpp',
+            'rendering/style/StyleFetchedImage.cpp',
+            'rendering/style/StyleFetchedImageSet.cpp',
+            'rendering/style/StyleFetchedShader.h',
+            'rendering/style/StyleFetchedShader.cpp',
             'rendering/style/StyleCustomFilterProgramCache.cpp',
             'rendering/style/StyleCustomFilterProgramCache.h',
             'rendering/style/StyleCustomFilterProgram.cpp',
@@ -1633,7 +1627,6 @@
             'workers/WorkerThread.cpp',
             'workers/WorkerThreadStartupData.cpp',
             'workers/WorkerThreadStartupData.h',
-            'xml/parser/CharacterReferenceParserInlines.h',
             'xml/parser/MarkupTokenizerInlines.h',
             'xml/parser/XMLDocumentParser.cpp',
             'xml/parser/XMLDocumentParser.h',
@@ -2116,6 +2109,9 @@
             'html/HTMLImport.h',
             'html/HTMLImportsController.cpp',
             'html/HTMLImportsController.h',
+            'html/HTMLImportLoader.cpp',
+            'html/HTMLImportLoader.h',
+            'html/HTMLImportLoaderClient.h',
             'html/HTMLInputElement.cpp',
             'html/HTMLKeygenElement.cpp',
             'html/HTMLKeygenElement.h',
@@ -2222,6 +2218,8 @@
             'html/LabelableElement.cpp',
             'html/LabelsNodeList.cpp',
             'html/LabelsNodeList.h',
+            'html/LinkImport.cpp',
+            'html/LinkImport.h',
             'html/LinkRelAttribute.cpp',
             'html/LinkRelAttribute.h',
             'html/LinkResource.cpp',
@@ -2586,8 +2584,6 @@
             'platform/ScrollableArea.cpp',
             'platform/Scrollbar.cpp',
             'platform/ScrollbarTheme.cpp',
-            'platform/ScrollbarThemeComposite.cpp',
-            'platform/ScrollbarThemeComposite.h',
             'platform/SecureTextInput.cpp',
             'platform/SecureTextInput.h',
             'platform/SerializedResource.h',
@@ -2705,7 +2701,6 @@
             'platform/chromium/ClipboardMimeTypes.h',
             'platform/chromium/ClipboardUtilitiesChromium.cpp',
             'platform/chromium/ClipboardUtilitiesChromium.h',
-            'platform/chromium/DragDataRef.h',
             'platform/chromium/FileSystemChromium.cpp',
             'platform/chromium/FramelessScrollView.cpp',
             'platform/chromium/FramelessScrollView.h',
@@ -2733,9 +2728,10 @@
             'platform/chromium/ScrollbarThemeChromium.cpp',
             'platform/chromium/ScrollbarThemeChromium.h',
             'platform/chromium/ScrollbarThemeChromiumAndroid.cpp',
-            'platform/chromium/ScrollbarThemeChromiumAndroid.h',
             'platform/chromium/ScrollbarThemeChromiumDefault.cpp',
             'platform/chromium/ScrollbarThemeChromiumDefault.h',
+            'platform/chromium/ScrollbarThemeChromiumOverlay.cpp',
+            'platform/chromium/ScrollbarThemeChromiumOverlay.h',
             'platform/chromium/ScrollbarThemeChromiumWin.cpp',
             'platform/chromium/ScrollbarThemeChromiumWin.h',
             'platform/chromium/SharedTimerChromium.cpp',
@@ -2898,8 +2894,6 @@
             'platform/graphics/filters/custom/ValidatedCustomFilterOperation.h',
             'platform/graphics/filters/DistantLightSource.cpp',
             'platform/graphics/filters/DistantLightSource.h',
-            'platform/graphics/filters/DropShadowImageFilter.cpp',
-            'platform/graphics/filters/DropShadowImageFilter.h',
             'platform/graphics/filters/FEBlend.cpp',
             'platform/graphics/filters/FEBlend.h',
             'platform/graphics/filters/FEColorMatrix.cpp',
@@ -3008,6 +3002,8 @@
             'platform/graphics/skia/SkiaUtils.cpp',
             'platform/graphics/skia/SkiaUtils.h',
             'platform/graphics/transforms/IdentityTransformOperation.h',
+            'platform/graphics/transforms/InterpolatedTransformOperation.h',
+            'platform/graphics/transforms/InterpolatedTransformOperation.cpp',
             'platform/graphics/transforms/Matrix3DTransformOperation.cpp',
             'platform/graphics/transforms/Matrix3DTransformOperation.h',
             'platform/graphics/transforms/MatrixTransformOperation.cpp',
@@ -3745,14 +3741,16 @@
             'animation/TimedItemTest.cpp',
             'css/CSSParserValuesTest.cpp',
             'html/TimeRangesTest.cpp',
-            'loader/cache/CachedImageTest.cpp',
+            'loader/cache/ImageResourceTest.cpp',
             'loader/cache/MemoryCacheTest.cpp',
             'loader/cache/ResourceFetcherTest.cpp',
+            'page/ImageBitmapTest.cpp',
             'platform/DecimalTest.cpp',
             'platform/SharedBufferTest.cpp',
             'platform/chromium/ClipboardChromiumTest.cpp',
             'platform/graphics/FontTest.cpp',
             'platform/graphics/GraphicsContextTest.cpp',
+            'platform/graphics/RoundedRectTest.cpp',
             'platform/graphics/UnitBezierTest.cpp',
             'platform/graphics/chromium/AnimationTranslationUtilTest.cpp',
             'platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp',
@@ -3768,6 +3766,7 @@
             'platform/image-decoders/gif/GIFImageDecoderTest.cpp',
             'platform/image-decoders/webp/WEBPImageDecoderTest.cpp',
             'platform/text/DateTimeFormatTest.cpp',
+            'rendering/RenderOverflowTest.cpp',
             'tests/ArenaTestHelpers.h',
             'tests/FakeWebGraphicsContext3D.h',
             'tests/HTMLDimension.cpp',
diff --git a/Source/core/css/CSSCrossfadeValue.cpp b/Source/core/css/CSSCrossfadeValue.cpp
index 7ca7b77..c48eaf2 100644
--- a/Source/core/css/CSSCrossfadeValue.cpp
+++ b/Source/core/css/CSSCrossfadeValue.cpp
@@ -27,10 +27,10 @@
 #include "core/css/CSSCrossfadeValue.h"
 
 #include "core/css/CSSImageValue.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/platform/graphics/CrossfadeGeneratedImage.h"
 #include "core/rendering/RenderObject.h"
-#include "core/rendering/style/StyleCachedImage.h"
+#include "core/rendering/style/StyleFetchedImage.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
@@ -61,17 +61,17 @@
     return false;
 }
 
-static CachedImage* cachedImageForCSSValue(CSSValue* value, ResourceFetcher* fetcher)
+static ImageResource* cachedImageForCSSValue(CSSValue* value, ResourceFetcher* fetcher)
 {
     if (!value)
         return 0;
 
     if (value->isImageValue()) {
-        StyleCachedImage* styleCachedImage = toCSSImageValue(value)->cachedImage(fetcher);
-        if (!styleCachedImage)
+        StyleFetchedImage* styleImageResource = toCSSImageValue(value)->cachedImage(fetcher);
+        if (!styleImageResource)
             return 0;
 
-        return styleCachedImage->cachedImage();
+        return styleImageResource->cachedImage();
     }
 
     if (value->isImageGeneratorValue()) {
@@ -112,8 +112,8 @@
     float inversePercentage = 1 - percentage;
 
     ResourceFetcher* fetcher = renderer->document()->fetcher();
-    CachedImage* cachedFromImage = cachedImageForCSSValue(m_fromValue.get(), fetcher);
-    CachedImage* cachedToImage = cachedImageForCSSValue(m_toValue.get(), fetcher);
+    ImageResource* cachedFromImage = cachedImageForCSSValue(m_fromValue.get(), fetcher);
+    ImageResource* cachedToImage = cachedImageForCSSValue(m_toValue.get(), fetcher);
 
     if (!cachedFromImage || !cachedToImage)
         return IntSize();
@@ -142,8 +142,8 @@
 
 void CSSCrossfadeValue::loadSubimages(ResourceFetcher* fetcher)
 {
-    ResourcePtr<CachedImage> oldCachedFromImage = m_cachedFromImage;
-    ResourcePtr<CachedImage> oldCachedToImage = m_cachedToImage;
+    ResourcePtr<ImageResource> oldCachedFromImage = m_cachedFromImage;
+    ResourcePtr<ImageResource> oldCachedToImage = m_cachedToImage;
 
     m_cachedFromImage = cachedImageForCSSValue(m_fromValue.get(), fetcher);
     m_cachedToImage = cachedImageForCSSValue(m_toValue.get(), fetcher);
@@ -171,8 +171,8 @@
         return 0;
 
     ResourceFetcher* fetcher = renderer->document()->fetcher();
-    CachedImage* cachedFromImage = cachedImageForCSSValue(m_fromValue.get(), fetcher);
-    CachedImage* cachedToImage = cachedImageForCSSValue(m_toValue.get(), fetcher);
+    ImageResource* cachedFromImage = cachedImageForCSSValue(m_fromValue.get(), fetcher);
+    ImageResource* cachedToImage = cachedImageForCSSValue(m_toValue.get(), fetcher);
 
     if (!cachedFromImage || !cachedToImage)
         return Image::nullImage();
@@ -197,7 +197,7 @@
     }
 }
 
-void CSSCrossfadeValue::CrossfadeSubimageObserverProxy::imageChanged(CachedImage*, const IntRect* rect)
+void CSSCrossfadeValue::CrossfadeSubimageObserverProxy::imageChanged(ImageResource*, const IntRect* rect)
 {
     if (m_ready)
         m_ownerValue->crossfadeChanged(*rect);
diff --git a/Source/core/css/CSSCrossfadeValue.h b/Source/core/css/CSSCrossfadeValue.h
index 9466315..450b615 100644
--- a/Source/core/css/CSSCrossfadeValue.h
+++ b/Source/core/css/CSSCrossfadeValue.h
@@ -28,14 +28,14 @@
 
 #include "core/css/CSSImageGeneratorValue.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/loader/cache/CachedImage.h"
-#include "core/loader/cache/CachedImageClient.h"
+#include "core/loader/cache/ImageResource.h"
+#include "core/loader/cache/ImageResourceClient.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/graphics/Image.h"
 
 namespace WebCore {
 
-class CachedImage;
+class ImageResource;
 class CrossfadeSubimageObserverProxy;
 class RenderObject;
 class Document;
@@ -76,14 +76,14 @@
         , m_cachedToImage(0)
         , m_crossfadeSubimageObserver(this) { }
 
-    class CrossfadeSubimageObserverProxy : public CachedImageClient {
+    class CrossfadeSubimageObserverProxy : public ImageResourceClient {
     public:
         CrossfadeSubimageObserverProxy(CSSCrossfadeValue* ownerValue)
         : m_ownerValue(ownerValue)
         , m_ready(false) { }
 
         virtual ~CrossfadeSubimageObserverProxy() { }
-        virtual void imageChanged(CachedImage*, const IntRect* = 0) OVERRIDE;
+        virtual void imageChanged(ImageResource*, const IntRect* = 0) OVERRIDE;
         void setReady(bool ready) { m_ready = ready; }
     private:
         CSSCrossfadeValue* m_ownerValue;
@@ -96,8 +96,8 @@
     RefPtr<CSSValue> m_toValue;
     RefPtr<CSSPrimitiveValue> m_percentageValue;
 
-    ResourcePtr<CachedImage> m_cachedFromImage;
-    ResourcePtr<CachedImage> m_cachedToImage;
+    ResourcePtr<ImageResource> m_cachedFromImage;
+    ResourcePtr<ImageResource> m_cachedToImage;
 
     RefPtr<Image> m_generatedImage;
 
diff --git a/Source/core/css/CSSCursorImageValue.cpp b/Source/core/css/CSSCursorImageValue.cpp
index 54d4f2a..21deed7 100644
--- a/Source/core/css/CSSCursorImageValue.cpp
+++ b/Source/core/css/CSSCursorImageValue.cpp
@@ -25,10 +25,10 @@
 #include "SVGNames.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSImageValue.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
-#include "core/rendering/style/StyleCachedImage.h"
-#include "core/rendering/style/StyleCachedImageSet.h"
+#include "core/rendering/style/StyleFetchedImage.h"
+#include "core/rendering/style/StyleFetchedImageSet.h"
 #include "core/rendering/style/StyleImage.h"
 #include "core/rendering/style/StylePendingImage.h"
 #include "core/svg/SVGCursorElement.h"
@@ -107,7 +107,7 @@
         m_hotSpot.setY(static_cast<int>(y));
 
         if (cachedImageURL() != element->document()->completeURL(cursorElement->hrefCurrentValue()))
-            clearCachedImage();
+            clearImageResource();
 
         SVGElement* svgElement = toSVGElement(element);
         m_referencedElements.add(svgElement);
@@ -135,7 +135,7 @@
             // FIXME: This will fail if the <cursor> element is in a shadow DOM (bug 59827)
             if (SVGCursorElement* cursorElement = resourceReferencedByCursorElement(imageValue->url(), loader->document())) {
                 RefPtr<CSSImageValue> svgImageValue = CSSImageValue::create(cursorElement->hrefCurrentValue());
-                StyleCachedImage* cachedImage = svgImageValue->cachedImage(loader);
+                StyleFetchedImage* cachedImage = svgImageValue->cachedImage(loader);
                 m_image = cachedImage;
                 return cachedImage;
             }
@@ -145,8 +145,8 @@
             m_image = toCSSImageValue(m_imageValue.get())->cachedImage(loader);
     }
 
-    if (m_image && m_image->isCachedImage())
-        return static_cast<StyleCachedImage*>(m_image.get());
+    if (m_image && m_image->isImageResource())
+        return static_cast<StyleFetchedImage*>(m_image.get());
 
     return 0;
 }
@@ -175,12 +175,12 @@
 
 String CSSCursorImageValue::cachedImageURL()
 {
-    if (!m_image || !m_image->isCachedImage())
+    if (!m_image || !m_image->isImageResource())
         return String();
-    return static_cast<StyleCachedImage*>(m_image.get())->cachedImage()->url().string();
+    return static_cast<StyleFetchedImage*>(m_image.get())->cachedImage()->url().string();
 }
 
-void CSSCursorImageValue::clearCachedImage()
+void CSSCursorImageValue::clearImageResource()
 {
     m_image = 0;
     m_accessedImage = false;
diff --git a/Source/core/css/CSSCursorImageValue.h b/Source/core/css/CSSCursorImageValue.h
index a1ee588..c4a895c 100644
--- a/Source/core/css/CSSCursorImageValue.h
+++ b/Source/core/css/CSSCursorImageValue.h
@@ -63,7 +63,7 @@
 
     bool isSVGCursor() const;
     String cachedImageURL();
-    void clearCachedImage();
+    void clearImageResource();
 
     RefPtr<CSSValue> m_imageValue;
 
diff --git a/Source/core/css/CSSFontFaceSource.cpp b/Source/core/css/CSSFontFaceSource.cpp
index 8f2dea2..1f160aa 100644
--- a/Source/core/css/CSSFontFaceSource.cpp
+++ b/Source/core/css/CSSFontFaceSource.cpp
@@ -28,7 +28,7 @@
 
 #include "core/css/CSSFontFace.h"
 #include "core/css/CSSFontSelector.h"
-#include "core/loader/cache/CachedFont.h"
+#include "core/loader/cache/FontResource.h"
 #include "core/platform/HistogramSupport.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/FontDescription.h"
@@ -44,7 +44,7 @@
 
 namespace WebCore {
 
-CSSFontFaceSource::CSSFontFaceSource(const String& str, CachedFont* font)
+CSSFontFaceSource::CSSFontFaceSource(const String& str, FontResource* font)
     : m_string(str)
     , m_font(font)
     , m_face(0)
@@ -85,15 +85,15 @@
     return true;
 }
 
-void CSSFontFaceSource::didStartFontLoad(CachedFont*)
+void CSSFontFaceSource::didStartFontLoad(FontResource*)
 {
     // Avoid duplicated reports when multiple CSSFontFaceSource are registered
-    // at this CachedFont.
+    // at this FontResource.
     if (!m_fontDataTable.isEmpty())
         m_histograms.loadStarted();
 }
 
-void CSSFontFaceSource::fontLoaded(CachedFont*)
+void CSSFontFaceSource::fontLoaded(FontResource*)
 {
     if (!m_fontDataTable.isEmpty())
         m_histograms.recordRemoteFont(m_font.get());
@@ -116,7 +116,7 @@
     ) {
         // We're local. Just return a SimpleFontData from the normal cache.
         // We don't want to check alternate font family names here, so pass true as the checkingAlternateName parameter.
-        RefPtr<SimpleFontData> fontData = fontCache()->getCachedFontData(fontDescription, m_string, true);
+        RefPtr<SimpleFontData> fontData = fontCache()->getFontResourceData(fontDescription, m_string, true);
         m_histograms.recordLocalFont(fontData);
         return fontData;
     }
@@ -248,7 +248,7 @@
     }
 }
 
-void CSSFontFaceSource::FontLoadHistograms::recordRemoteFont(const CachedFont* font)
+void CSSFontFaceSource::FontLoadHistograms::recordRemoteFont(const FontResource* font)
 {
     if (m_loadStartTime > 0 && font && !font->isLoading()) {
         int duration = static_cast<int>(currentTimeMS() - m_loadStartTime);
@@ -257,7 +257,7 @@
     }
 }
 
-const char* CSSFontFaceSource::FontLoadHistograms::histogramName(const CachedFont* font)
+const char* CSSFontFaceSource::FontLoadHistograms::histogramName(const FontResource* font)
 {
     if (font->errorOccurred())
         return "WebFont.DownloadTime.LoadError";
diff --git a/Source/core/css/CSSFontFaceSource.h b/Source/core/css/CSSFontFaceSource.h
index 75a02d5..aea2ac5 100644
--- a/Source/core/css/CSSFontFaceSource.h
+++ b/Source/core/css/CSSFontFaceSource.h
@@ -26,7 +26,7 @@
 #ifndef CSSFontFaceSource_h
 #define CSSFontFaceSource_h
 
-#include "core/loader/cache/CachedFont.h"
+#include "core/loader/cache/FontResource.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "wtf/HashMap.h"
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-class CachedFont;
+class FontResource;
 class CSSFontFace;
 class CSSFontSelector;
 class FontDescription;
@@ -45,9 +45,9 @@
 #endif
 
 
-class CSSFontFaceSource : public CachedFontClient {
+class CSSFontFaceSource : public FontResourceClient {
 public:
-    CSSFontFaceSource(const String&, CachedFont* = 0);
+    CSSFontFaceSource(const String&, FontResource* = 0);
     virtual ~CSSFontFaceSource();
 
     bool isLoaded() const;
@@ -57,8 +57,8 @@
 
     void setFontFace(CSSFontFace* face) { m_face = face; }
 
-    virtual void didStartFontLoad(CachedFont*) OVERRIDE;
-    virtual void fontLoaded(CachedFont*);
+    virtual void didStartFontLoad(FontResource*) OVERRIDE;
+    virtual void fontLoaded(FontResource*);
 
     PassRefPtr<SimpleFontData> getFontData(const FontDescription&, bool syntheticBold, bool syntheticItalic, CSSFontSelector*);
 
@@ -80,16 +80,16 @@
         FontLoadHistograms() : m_loadStartTime(0) { }
         void loadStarted();
         void recordLocalFont(bool loadSuccess);
-        void recordRemoteFont(const CachedFont*);
+        void recordRemoteFont(const FontResource*);
     private:
-        const char* histogramName(const CachedFont*);
+        const char* histogramName(const FontResource*);
         double m_loadStartTime;
     };
 
     void startLoadingTimerFired(Timer<CSSFontFaceSource>*);
 
     AtomicString m_string; // URI for remote, built-in font name for local.
-    ResourcePtr<CachedFont> m_font; // For remote fonts, a pointer to our cached resource.
+    ResourcePtr<FontResource> m_font; // For remote fonts, a pointer to our cached resource.
     CSSFontFace* m_face; // Our owning font face.
     HashMap<unsigned, RefPtr<SimpleFontData> > m_fontDataTable; // The hash key is composed of size synthetic styles.
     FontLoadHistograms m_histograms;
diff --git a/Source/core/css/CSSFontFaceSrcValue.cpp b/Source/core/css/CSSFontFaceSrcValue.cpp
index 51e2f90..46fd349 100644
--- a/Source/core/css/CSSFontFaceSrcValue.cpp
+++ b/Source/core/css/CSSFontFaceSrcValue.cpp
@@ -30,8 +30,8 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
 #include "core/dom/Node.h"
-#include "core/loader/cache/CachedFont.h"
 #include "core/loader/cache/FetchRequest.h"
+#include "core/loader/cache/FontResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/platform/graphics/FontCustomPlatformData.h"
 #include "core/svg/SVGFontFaceElement.h"
@@ -89,18 +89,18 @@
 
 bool CSSFontFaceSrcValue::hasFailedOrCanceledSubresources() const
 {
-    if (!m_cachedFont)
+    if (!m_fetched)
         return false;
-    return m_cachedFont->loadFailedOrCanceled();
+    return m_fetched->loadFailedOrCanceled();
 }
 
-CachedFont* CSSFontFaceSrcValue::cachedFont(Document* document)
+FontResource* CSSFontFaceSrcValue::fetch(Document* document)
 {
-    if (!m_cachedFont) {
+    if (!m_fetched) {
         FetchRequest request(ResourceRequest(document->completeURL(m_resource)), FetchInitiatorTypeNames::css);
-        m_cachedFont = document->fetcher()->requestFont(request);
+        m_fetched = document->fetcher()->requestFont(request);
     }
-    return m_cachedFont.get();
+    return m_fetched.get();
 }
 
 bool CSSFontFaceSrcValue::equals(const CSSFontFaceSrcValue& other) const
diff --git a/Source/core/css/CSSFontFaceSrcValue.h b/Source/core/css/CSSFontFaceSrcValue.h
index 3b96bd2..023e38e 100644
--- a/Source/core/css/CSSFontFaceSrcValue.h
+++ b/Source/core/css/CSSFontFaceSrcValue.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class CachedFont;
+class FontResource;
 class Document;
 class SVGFontFaceElement;
 
@@ -69,7 +69,7 @@
 
     bool hasFailedOrCanceledSubresources() const;
 
-    CachedFont* cachedFont(Document*);
+    FontResource* fetch(Document*);
 
     bool equals(const CSSFontFaceSrcValue&) const;
 
@@ -88,7 +88,7 @@
     String m_format;
     bool m_isLocal;
 
-    ResourcePtr<CachedFont> m_cachedFont;
+    ResourcePtr<FontResource> m_fetched;
 
 #if ENABLE(SVG_FONTS)
     SVGFontFaceElement* m_svgFontFaceElement;
diff --git a/Source/core/css/CSSFontSelector.cpp b/Source/core/css/CSSFontSelector.cpp
index 5bdd10c..f721acd 100644
--- a/Source/core/css/CSSFontSelector.cpp
+++ b/Source/core/css/CSSFontSelector.cpp
@@ -44,7 +44,7 @@
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/cache/CachedFont.h"
+#include "core/loader/cache/FontResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Frame.h"
 #include "core/page/Settings.h"
@@ -211,9 +211,9 @@
             Settings* settings = m_document ? m_document->frame() ? m_document->frame()->settings() : 0 : 0;
             bool allowDownloading = foundSVGFont || (settings && settings->downloadableBinaryFontsEnabled());
             if (allowDownloading && item->isSupportedFormat() && m_document) {
-                CachedFont* cachedFont = item->cachedFont(m_document);
-                if (cachedFont) {
-                    source = adoptPtr(new CSSFontFaceSource(item->resource(), cachedFont));
+                FontResource* fetched = item->fetch(m_document);
+                if (fetched) {
+                    source = adoptPtr(new CSSFontFaceSource(item->resource(), fetched));
 #if ENABLE(SVG_FONTS)
                     if (foundSVGFont)
                         source->setHasExternalSVGFont(true);
@@ -379,7 +379,7 @@
          genericFamily = settings->standardFontFamily(script);
 
     if (!genericFamily.isEmpty())
-        return fontCache()->getCachedFontData(fontDescription, genericFamily);
+        return fontCache()->getFontResourceData(fontDescription, genericFamily);
 
     return 0;
 }
@@ -567,7 +567,7 @@
     m_document = 0;
 }
 
-void CSSFontSelector::beginLoadingFontSoon(CachedFont* font)
+void CSSFontSelector::beginLoadingFontSoon(FontResource* font)
 {
     if (!m_document)
         return;
@@ -582,7 +582,7 @@
 
 void CSSFontSelector::beginLoadTimerFired(Timer<WebCore::CSSFontSelector>*)
 {
-    Vector<ResourcePtr<CachedFont> > fontsToBeginLoading;
+    Vector<ResourcePtr<FontResource> > fontsToBeginLoading;
     fontsToBeginLoading.swap(m_fontsToBeginLoading);
 
     // CSSFontSelector could get deleted via beginLoadIfNeeded() or loadDone() unless protected.
diff --git a/Source/core/css/CSSFontSelector.h b/Source/core/css/CSSFontSelector.h
index a8a77be..8d41ad2 100644
--- a/Source/core/css/CSSFontSelector.h
+++ b/Source/core/css/CSSFontSelector.h
@@ -39,7 +39,7 @@
 class CSSFontFace;
 class CSSFontFaceRule;
 class CSSSegmentedFontFace;
-class CachedFont;
+class FontResource;
 class Document;
 class FontDescription;
 class StyleRuleFontFace;
@@ -71,7 +71,7 @@
 
     Document* document() const { return m_document; }
 
-    void beginLoadingFontSoon(CachedFont*);
+    void beginLoadingFontSoon(FontResource*);
 
 private:
     CSSFontSelector(Document*);
@@ -86,7 +86,7 @@
     HashMap<String, OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >, CaseFoldingHash> m_fonts;
     HashSet<FontSelectorClient*> m_clients;
 
-    Vector<ResourcePtr<CachedFont> > m_fontsToBeginLoading;
+    Vector<ResourcePtr<FontResource> > m_fontsToBeginLoading;
     Timer<CSSFontSelector> m_beginLoadingTimer;
 
     unsigned m_version;
diff --git a/Source/core/css/CSSGrammar.y.in b/Source/core/css/CSSGrammar.y.in
index 4ef806b..adb38a6 100644
--- a/Source/core/css/CSSGrammar.y.in
+++ b/Source/core/css/CSSGrammar.y.in
@@ -73,6 +73,7 @@
     case URI:
     case FUNCTION:
     case ANYFUNCTION:
+    case HOSTFUNCTION:
     case NOTFUNCTION:
     case CALCFUNCTION:
     case MINFUNCTION:
@@ -217,6 +218,7 @@
 %token <string> VARFUNCTION
 %token <string> VAR_DEFINITION
 %token <string> PARTFUNCTION
+%token <string> HOSTFUNCTION
 
 %token <string> UNICODERANGE
 
@@ -1512,6 +1514,29 @@
     | ':' ':' PARTFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
+    | ':' HOSTFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
+        $$ = parser->createFloatingSelector();
+        $$->setMatch(CSSSelector::PseudoClass);
+        $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($4));
+        parser->tokenToLowerCase($2);
+        $$->setValue($2);
+        CSSSelector::PseudoType type = $$->pseudoType();
+        if (type != CSSSelector::PseudoHost)
+            YYERROR;
+    }
+    //  used by :host()
+    | ':' HOSTFUNCTION maybe_space closing_parenthesis {
+        $$ = parser->createFloatingSelector();
+        $$->setMatch(CSSSelector::PseudoClass);
+        parser->tokenToLowerCase($2);
+        $$->setValue($2.atomicSubstring(0, $2.length() - 1));
+        CSSSelector::PseudoType type = $$->pseudoType();
+        if (type != CSSSelector::PseudoHost)
+            YYERROR;
+    }
+    | ':' HOSTFUNCTION selector_recovery closing_parenthesis {
+        YYERROR;
+    }
   ;
 
 selector_recovery:
@@ -1857,7 +1882,7 @@
     opening_parenthesis error_recovery closing_parenthesis;
 
 opening_parenthesis:
-    '(' | FUNCTION | CALCFUNCTION | VARFUNCTION | MINFUNCTION | MAXFUNCTION | ANYFUNCTION | NOTFUNCTION | CUEFUNCTION | DISTRIBUTEDFUNCTION
+    '(' | FUNCTION | CALCFUNCTION | VARFUNCTION | MINFUNCTION | MAXFUNCTION | ANYFUNCTION | NOTFUNCTION | CUEFUNCTION | DISTRIBUTEDFUNCTION | HOSTFUNCTION
     ;
 
 error_location: {
diff --git a/Source/core/css/CSSGridTemplateValue.cpp b/Source/core/css/CSSGridTemplateValue.cpp
index 2348305..b54805c 100644
--- a/Source/core/css/CSSGridTemplateValue.cpp
+++ b/Source/core/css/CSSGridTemplateValue.cpp
@@ -71,13 +71,13 @@
 {
     StringBuilder builder;
     for (size_t row = 0; row < m_rowCount; ++row) {
-        builder.append('\'');
+        builder.append('\"');
         for (size_t column = 0; column < m_columnCount; ++column) {
             builder.append(stringForPosition(m_gridAreaMap, row, column));
             if (column != m_columnCount - 1)
                 builder.append(' ');
         }
-        builder.append('\'');
+        builder.append('\"');
         if (row != m_rowCount - 1)
             builder.append(' ');
     }
diff --git a/Source/core/css/CSSImageSetValue.cpp b/Source/core/css/CSSImageSetValue.cpp
index 93d9e8b..efae646 100644
--- a/Source/core/css/CSSImageSetValue.cpp
+++ b/Source/core/css/CSSImageSetValue.cpp
@@ -30,10 +30,10 @@
 #include "core/css/CSSImageValue.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedImage.h"
 #include "core/loader/cache/FetchRequest.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
-#include "core/rendering/style/StyleCachedImageSet.h"
+#include "core/rendering/style/StyleFetchedImageSet.h"
 #include "core/rendering/style/StylePendingImage.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -48,8 +48,8 @@
 
 CSSImageSetValue::~CSSImageSetValue()
 {
-    if (m_imageSet && m_imageSet->isCachedImageSet())
-        static_cast<StyleCachedImageSet*>(m_imageSet.get())->clearImageSetValue();
+    if (m_imageSet && m_imageSet->isImageResourceSet())
+        static_cast<StyleFetchedImageSet*>(m_imageSet.get())->clearImageSetValue();
 }
 
 void CSSImageSetValue::fillImageSet()
@@ -88,7 +88,7 @@
     return image;
 }
 
-StyleCachedImageSet* CSSImageSetValue::cachedImageSet(ResourceFetcher* loader, float deviceScaleFactor)
+StyleFetchedImageSet* CSSImageSetValue::cachedImageSet(ResourceFetcher* loader, float deviceScaleFactor)
 {
     ASSERT(loader);
 
@@ -104,14 +104,14 @@
         ImageWithScale image = bestImageForScaleFactor();
         if (Document* document = loader->document()) {
             FetchRequest request(ResourceRequest(document->completeURL(image.imageURL)), FetchInitiatorTypeNames::css);
-            if (ResourcePtr<CachedImage> cachedImage = loader->requestImage(request)) {
-                m_imageSet = StyleCachedImageSet::create(cachedImage.get(), image.scaleFactor, this);
+            if (ResourcePtr<ImageResource> cachedImage = loader->requestImage(request)) {
+                m_imageSet = StyleFetchedImageSet::create(cachedImage.get(), image.scaleFactor, this);
                 m_accessedBestFitImage = true;
             }
         }
     }
 
-    return (m_imageSet && m_imageSet->isCachedImageSet()) ? static_cast<StyleCachedImageSet*>(m_imageSet.get()) : 0;
+    return (m_imageSet && m_imageSet->isImageResourceSet()) ? static_cast<StyleFetchedImageSet*>(m_imageSet.get()) : 0;
 }
 
 StyleImage* CSSImageSetValue::cachedOrPendingImageSet(float deviceScaleFactor)
@@ -161,9 +161,9 @@
 
 bool CSSImageSetValue::hasFailedOrCanceledSubresources() const
 {
-    if (!m_imageSet || !m_imageSet->isCachedImageSet())
+    if (!m_imageSet || !m_imageSet->isImageResourceSet())
         return false;
-    Resource* cachedResource = static_cast<StyleCachedImageSet*>(m_imageSet.get())->cachedImage();
+    Resource* cachedResource = static_cast<StyleFetchedImageSet*>(m_imageSet.get())->cachedImage();
     if (!cachedResource)
         return true;
     return cachedResource->loadFailedOrCanceled();
diff --git a/Source/core/css/CSSImageSetValue.h b/Source/core/css/CSSImageSetValue.h
index db030aa..42fdae9 100644
--- a/Source/core/css/CSSImageSetValue.h
+++ b/Source/core/css/CSSImageSetValue.h
@@ -31,7 +31,7 @@
 namespace WebCore {
 
 class ResourceFetcher;
-class StyleCachedImageSet;
+class StyleFetchedImageSet;
 class StyleImage;
 
 class CSSImageSetValue : public CSSValueList {
@@ -43,9 +43,9 @@
     }
     ~CSSImageSetValue();
 
-    StyleCachedImageSet* cachedImageSet(ResourceFetcher*, float deviceScaleFactor);
+    StyleFetchedImageSet* cachedImageSet(ResourceFetcher*, float deviceScaleFactor);
 
-    // Returns a StyleCachedImageSet if the best fit image has been cached already, otherwise a StylePendingImage.
+    // Returns a StyleFetchedImageSet if the best fit image has been cached already, otherwise a StylePendingImage.
     StyleImage* cachedOrPendingImageSet(float);
 
     String customCssText() const;
diff --git a/Source/core/css/CSSImageValue.cpp b/Source/core/css/CSSImageValue.cpp
index 871934d..afd9659 100644
--- a/Source/core/css/CSSImageValue.cpp
+++ b/Source/core/css/CSSImageValue.cpp
@@ -24,10 +24,10 @@
 #include "FetchInitiatorTypeNames.h"
 #include "core/css/CSSParser.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedImage.h"
 #include "core/loader/cache/FetchRequest.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
-#include "core/rendering/style/StyleCachedImage.h"
+#include "core/rendering/style/StyleFetchedImage.h"
 #include "core/rendering/style/StylePendingImage.h"
 
 namespace WebCore {
@@ -59,7 +59,7 @@
     return m_image.get();
 }
 
-StyleCachedImage* CSSImageValue::cachedImage(ResourceFetcher* loader, const ResourceLoaderOptions& options)
+StyleFetchedImage* CSSImageValue::cachedImage(ResourceFetcher* loader, const ResourceLoaderOptions& options)
 {
     ASSERT(loader);
 
@@ -67,18 +67,18 @@
         m_accessedImage = true;
 
         FetchRequest request(ResourceRequest(loader->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, options);
-        if (ResourcePtr<CachedImage> cachedImage = loader->requestImage(request))
-            m_image = StyleCachedImage::create(cachedImage.get());
+        if (ResourcePtr<ImageResource> cachedImage = loader->requestImage(request))
+            m_image = StyleFetchedImage::create(cachedImage.get());
     }
 
-    return (m_image && m_image->isCachedImage()) ? static_cast<StyleCachedImage*>(m_image.get()) : 0;
+    return (m_image && m_image->isImageResource()) ? static_cast<StyleFetchedImage*>(m_image.get()) : 0;
 }
 
 bool CSSImageValue::hasFailedOrCanceledSubresources() const
 {
-    if (!m_image || !m_image->isCachedImage())
+    if (!m_image || !m_image->isImageResource())
         return false;
-    Resource* cachedResource = static_cast<StyleCachedImage*>(m_image.get())->cachedImage();
+    Resource* cachedResource = static_cast<StyleFetchedImage*>(m_image.get())->cachedImage();
     if (!cachedResource)
         return true;
     return cachedResource->loadFailedOrCanceled();
diff --git a/Source/core/css/CSSImageValue.h b/Source/core/css/CSSImageValue.h
index f05134b..1a9b3ea 100644
--- a/Source/core/css/CSSImageValue.h
+++ b/Source/core/css/CSSImageValue.h
@@ -28,7 +28,7 @@
 namespace WebCore {
 
 class Element;
-class StyleCachedImage;
+class StyleFetchedImage;
 class StyleImage;
 class RenderObject;
 
@@ -38,9 +38,9 @@
     static PassRefPtr<CSSImageValue> create(const String& url, StyleImage* image) { return adoptRef(new CSSImageValue(url, image)); }
     ~CSSImageValue();
 
-    StyleCachedImage* cachedImage(ResourceFetcher*, const ResourceLoaderOptions&);
-    StyleCachedImage* cachedImage(ResourceFetcher* loader) { return cachedImage(loader, ResourceFetcher::defaultResourceOptions()); }
-    // Returns a StyleCachedImage if the image is cached already, otherwise a StylePendingImage.
+    StyleFetchedImage* cachedImage(ResourceFetcher*, const ResourceLoaderOptions&);
+    StyleFetchedImage* cachedImage(ResourceFetcher* loader) { return cachedImage(loader, ResourceFetcher::defaultResourceOptions()); }
+    // Returns a StyleFetchedImage if the image is cached already, otherwise a StylePendingImage.
     StyleImage* cachedOrPendingImage();
 
     const String& url() { return m_url; }
diff --git a/Source/core/css/CSSImportRule.h b/Source/core/css/CSSImportRule.h
index ab9fd00..a4ccaf4 100644
--- a/Source/core/css/CSSImportRule.h
+++ b/Source/core/css/CSSImportRule.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class CachedCSSStyleSheet;
+class CSSStyleSheetResource;
 class MediaList;
 class MediaQuerySet;
 class StyleRuleImport;
diff --git a/Source/core/css/CSSParser-in.cpp b/Source/core/css/CSSParser-in.cpp
index d2486d9..a25c6de 100644
--- a/Source/core/css/CSSParser-in.cpp
+++ b/Source/core/css/CSSParser-in.cpp
@@ -10026,6 +10026,10 @@
             m_token = CALCFUNCTION;
             return true;
         }
+        CASE("host") {
+            m_token = HOSTFUNCTION;
+            return true;
+        }
         CASE("nth-child") {
             m_parsingMode = NthChildMode;
             return true;
diff --git a/Source/core/css/CSSProperties.in b/Source/core/css/CSSProperties.in
index b8f4c2c..1520238 100644
--- a/Source/core/css/CSSProperties.in
+++ b/Source/core/css/CSSProperties.in
@@ -17,10 +17,10 @@
 background-repeat-y custom_all
 background-size custom_all
 border-bottom-color custom_all
-border-bottom-left-radius initial=initialBorderRadius, custom_value
-border-bottom-right-radius initial=initialBorderRadius, custom_value
+border-bottom-left-radius type_name=LengthSize, initial=initialBorderRadius, converter=convertRadius
+border-bottom-right-radius type_name=LengthSize, initial=initialBorderRadius, converter=convertRadius
 border-bottom-style type_name=EBorderStyle, initial=initialBorderStyle
-border-bottom-width type_name=unsigned, initial=initialBorderWidth, custom_value
+border-bottom-width type_name=unsigned, initial=initialBorderWidth, converter=convertLineWidth<unsigned>
 border-collapse
 border-image-outset custom_all
 border-image-repeat custom_all
@@ -29,16 +29,16 @@
 border-image-width custom_all
 border-left-color custom_all
 border-left-style type_name=EBorderStyle, initial=initialBorderStyle
-border-left-width type_name=unsigned, initial=initialBorderWidth, custom_value
+border-left-width type_name=unsigned, initial=initialBorderWidth, converter=convertLineWidth<unsigned>
 border-right-color custom_all
 border-right-style type_name=EBorderStyle, initial=initialBorderStyle
-border-right-width type_name=unsigned, initial=initialBorderWidth, custom_value
+border-right-width type_name=unsigned, initial=initialBorderWidth, converter=convertLineWidth<unsigned>
 border-top-color custom_all
-border-top-left-radius initial=initialBorderRadius, custom_value
-border-top-right-radius initial=initialBorderRadius, custom_value
+border-top-left-radius type_name=LengthSize, initial=initialBorderRadius, converter=convertRadius
+border-top-right-radius type_name=LengthSize, initial=initialBorderRadius, converter=convertRadius
 border-top-style type_name=EBorderStyle, initial=initialBorderStyle
-border-top-width type_name=unsigned, initial=initialBorderWidth, custom_value
-bottom apply_type=length, initial=initialOffset, use_auto
+border-top-width type_name=unsigned, initial=initialBorderWidth, converter=convertLineWidth<unsigned>
+bottom type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
 box-sizing
 caption-side
 clear
@@ -50,7 +50,7 @@
 direction custom_value
 display custom_inherit, custom_value
 empty-cells type_name=EEmptyCell
-flex-basis apply_type=length, use_auto
+flex-basis type_name=Length, converter=convertLengthOrAuto
 flex-direction
 flex-grow type_name=float
 flex-shrink type_name=float
@@ -62,45 +62,45 @@
 font-variant custom_all
 font-weight custom_all
 grid-auto-flow type_name=GridAutoFlow
-height apply_type=length, initial=initialSize, use_auto, use_intrinsic
+height type_name=Length, initial=initialSize, converter=convertLengthSizing
 justify-content
 image-rendering
-left apply_type=length, initial=initialOffset, use_auto
-letter-spacing type_name=float, initial=initialLetterWordSpacing, custom_value
+left type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
+letter-spacing type_name=float, initial=initialLetterWordSpacing, converter=convertSpacing
 line-height getter=specifiedLineHeight, custom_value
 list-style-image type_name=StyleImage*, custom_value
 list-style-position
 list-style-type
-margin-bottom apply_type=length, initial=initialMargin, use_auto
-margin-left apply_type=length, initial=initialMargin, use_auto
-margin-right apply_type=length, initial=initialMargin, use_auto
-margin-top apply_type=length, initial=initialMargin, use_auto
-max-height apply_type=length, initial=initialMaxSize, use_auto, use_intrinsic, use_none
-max-width apply_type=length, initial=initialMaxSize, use_auto, use_intrinsic, use_none
-min-height apply_type=length, initial=initialMinSize, use_auto, use_intrinsic
-min-width apply_type=length, initial=initialMinSize, use_auto, use_intrinsic
+margin-bottom type_name=Length, initial=initialMargin, converter=convertLengthOrAuto
+margin-left type_name=Length, initial=initialMargin, converter=convertLengthOrAuto
+margin-right type_name=Length, initial=initialMargin, converter=convertLengthOrAuto
+margin-top type_name=Length, initial=initialMargin, converter=convertLengthOrAuto
+max-height type_name=Length, initial=initialMaxSize, converter=convertLengthMaxSizing
+max-width type_name=Length, initial=initialMaxSize, converter=convertLengthMaxSizing
+min-height type_name=Length, initial=initialMinSize, converter=convertLengthSizing
+min-width type_name=Length, initial=initialMinSize, converter=convertLengthSizing
 mix-blend-mode type_name=BlendMode, name_for_methods=BlendMode
 opacity type_name=float
 order type_name=int
 orphans type_name=short, custom_all
 outline-color custom_all
-outline-offset type_name=int, custom_value
+outline-offset type_name=int, converter=convertComputedLength<int>
 outline-style custom_all
-outline-width type_name=unsigned short, custom_value
+outline-width type_name=unsigned short, converter=convertLineWidth<unsigned short>
 overflow-wrap
 overflow-x type_name=EOverflow
 overflow-y type_name=EOverflow
-padding-bottom apply_type=length, initial=initialPadding
-padding-left apply_type=length, initial=initialPadding
-padding-right apply_type=length, initial=initialPadding
-padding-top apply_type=length, initial=initialPadding
+padding-bottom type_name=Length, initial=initialPadding, converter=convertLength
+padding-left type_name=Length, initial=initialPadding, converter=convertLength
+padding-right type_name=Length, initial=initialPadding, converter=convertLength
+padding-top type_name=Length, initial=initialPadding, converter=convertLength
 page-break-after type_name=EPageBreak, initial=initialPageBreak
 page-break-before type_name=EPageBreak, initial=initialPageBreak
 page-break-inside type_name=EPageBreak, initial=initialPageBreak
 pointer-events
 position
 resize custom_value
-right apply_type=length, initial=initialOffset, use_auto
+right type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
 size custom_all
 speak
 table-layout
@@ -115,16 +115,16 @@
 text-overflow type_name=TextOverflow
 text-rendering custom_all
 text-transform
-top apply_type=length, initial=initialOffset, use_auto
+top type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
 touch-action type_name=TouchAction, initial=initialTouchAction
 unicode-bidi
 vertical-align custom_value
 visibility
 white-space
 widows type_name=short, custom_all
-width apply_type=length, initial=initialSize, use_auto, use_intrinsic
+width type_name=Length, initial=initialSize, converter=convertLengthSizing
 word-break
-word-spacing type_name=float, initial=initialLetterWordSpacing, custom_value
+word-spacing type_name=float, initial=initialLetterWordSpacing, converter=convertSpacing
 // UAs must treat 'word-wrap' as an alternate name for the 'overflow-wrap' property. So using the same handlers.
 word-wrap name_for_methods=OverflowWrap
 zoom custom_all
@@ -146,9 +146,9 @@
 -webkit-background-origin use_handlers_for=CSSPropertyBackgroundOrigin
 -webkit-background-size use_handlers_for=CSSPropertyBackgroundSize
 -webkit-border-fit
--webkit-border-horizontal-spacing type_name=short, name_for_methods=HorizontalBorderSpacing, custom_value
+-webkit-border-horizontal-spacing type_name=short, name_for_methods=HorizontalBorderSpacing, converter=convertComputedLength<short>
 -webkit-border-image initial=initialNinePieceImage, custom_value
--webkit-border-vertical-spacing type_name=short, name_for_methods=VerticalBorderSpacing, custom_value
+-webkit-border-vertical-spacing type_name=short, name_for_methods=VerticalBorderSpacing, converter=convertComputedLength<short>
 -webkit-box-align type_name=EBoxAlignment
 -webkit-box-decoration-break
 -webkit-box-direction
@@ -168,20 +168,20 @@
 -webkit-column-progression type_name=ColumnProgression
 -webkit-column-rule-color custom_all
 -webkit-column-rule-style type_name=EBorderStyle, initial=initialBorderStyle
--webkit-column-rule-width type_name=unsigned short, custom_value
+-webkit-column-rule-width type_name=unsigned short, converter=convertLineWidth<unsigned short>
 -webkit-column-span type_name=ColumnSpan
 -webkit-column-width type_name=float, custom_all
--webkit-flow-from type_name=const AtomicString&, name_for_methods=RegionThread, custom_value
--webkit-flow-into type_name=const AtomicString&, name_for_methods=FlowThread, custom_value
+-webkit-flow-from type_name=AtomicString, name_for_methods=RegionThread, converter=convertString<CSSValueNone>
+-webkit-flow-into type_name=AtomicString, name_for_methods=FlowThread, converter=convertString<CSSValueNone>
 -webkit-font-kerning custom_all
 -webkit-font-smoothing custom_all
 -webkit-font-variant-ligatures custom_all
--webkit-highlight type_name=const AtomicString&, custom_value
--webkit-hyphenate-character type_name=const AtomicString&, name_for_methods=HyphenationString, custom_value
+-webkit-highlight type_name=AtomicString, converter=convertString<CSSValueNone>
+-webkit-hyphenate-character type_name=AtomicString, name_for_methods=HyphenationString, converter=convertString<CSSValueAuto>
 -webkit-line-align type_name=LineAlign
 -webkit-line-break type_name=LineBreak
 -webkit-line-clamp type_name=LineClampValue
--webkit-line-grid type_name=const AtomicString&, custom_value
+-webkit-line-grid type_name=AtomicString, converter=convertString<CSSValueNone>
 -webkit-line-snap type_name=LineSnap
 -webkit-margin-after-collapse type_name=EMarginCollapse
 -webkit-margin-before-collapse type_name=EMarginCollapse
@@ -208,8 +208,8 @@
 -webkit-mask-repeat-y custom_all
 -webkit-mask-size custom_all
 -webkit-perspective-origin custom_all
--webkit-perspective-origin-x apply_type=length
--webkit-perspective-origin-y apply_type=length
+-webkit-perspective-origin-x type_name=Length, converter=convertLength
+-webkit-perspective-origin-y type_name=Length, converter=convertLength
 -webkit-print-color-adjust type_name=PrintColorAdjust
 -webkit-region-break-after type_name=EPageBreak, initial=initialPageBreak
 -webkit-region-break-before type_name=EPageBreak, initial=initialPageBreak
@@ -218,9 +218,9 @@
 -webkit-rtl-ordering type_name=Order, getter=rtlOrdering, setter=setRTLOrdering, initial=initialRTLOrdering
 -webkit-ruby-position type_name=RubyPosition
 -webkit-shape-inside type_name=ShapeValue*, custom_value
--webkit-shape-margin apply_type=length
+-webkit-shape-margin type_name=Length, converter=convertLength
 -webkit-shape-outside type_name=ShapeValue*, custom_value
--webkit-shape-padding apply_type=length
+-webkit-shape-padding type_name=Length, converter=convertLength
 -webkit-text-combine type_name=TextCombine
 -webkit-text-emphasis-color custom_all
 -webkit-text-emphasis-position type_name=TextEmphasisPosition
@@ -229,9 +229,9 @@
 -webkit-text-security
 -webkit-text-stroke-color custom_all
 -webkit-text-underline-position custom_value, condition=CSS3_TEXT
--webkit-transform-origin-x apply_type=length
--webkit-transform-origin-y apply_type=length
--webkit-transform-origin-z type_name=float, custom_value
+-webkit-transform-origin-x type_name=Length, converter=convertLength
+-webkit-transform-origin-y type_name=Length, converter=convertLength
+-webkit-transform-origin-z type_name=float, converter=convertComputedLength<float>
 -webkit-transform-style name_for_methods=TransformStyle3D
 -webkit-transition-delay custom_all
 -webkit-transition-duration custom_all
diff --git a/Source/core/css/CSSPropertySourceData.cpp b/Source/core/css/CSSPropertySourceData.cpp
index 87a77ff..6a5ff1b 100644
--- a/Source/core/css/CSSPropertySourceData.cpp
+++ b/Source/core/css/CSSPropertySourceData.cpp
@@ -91,7 +91,7 @@
 
 String CSSPropertySourceData::toString() const
 {
-    DEFINE_STATIC_LOCAL(String, emptyValue, (ASCIILiteral("e")));
+    DEFINE_STATIC_LOCAL(String, emptyValue, ("e"));
     if (!name && value == emptyValue)
         return String();
 
diff --git a/Source/core/css/CSSSVGDocumentValue.cpp b/Source/core/css/CSSSVGDocumentValue.cpp
index 1963cba..38a9874 100644
--- a/Source/core/css/CSSSVGDocumentValue.cpp
+++ b/Source/core/css/CSSSVGDocumentValue.cpp
@@ -29,7 +29,7 @@
 #include "FetchInitiatorTypeNames.h"
 #include "core/css/CSSParser.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedDocument.h"
+#include "core/loader/cache/DocumentResource.h"
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/ResourceFetcher.h"
 
@@ -46,7 +46,7 @@
 {
 }
 
-CachedDocument* CSSSVGDocumentValue::load(ResourceFetcher* loader)
+DocumentResource* CSSSVGDocumentValue::load(ResourceFetcher* loader)
 {
     ASSERT(loader);
 
diff --git a/Source/core/css/CSSSVGDocumentValue.h b/Source/core/css/CSSSVGDocumentValue.h
index b702245..5f13221 100644
--- a/Source/core/css/CSSSVGDocumentValue.h
+++ b/Source/core/css/CSSSVGDocumentValue.h
@@ -26,7 +26,7 @@
 #define CSSSVGDocumentValue_h
 
 #include "core/css/CSSValue.h"
-#include "core/loader/cache/CachedDocument.h"
+#include "core/loader/cache/DocumentResource.h"
 #include "core/loader/cache/ResourcePtr.h"
 
 namespace WebCore {
@@ -38,8 +38,8 @@
     static PassRefPtr<CSSSVGDocumentValue> create(const String& url) { return adoptRef(new CSSSVGDocumentValue(url)); }
     ~CSSSVGDocumentValue();
 
-    CachedDocument* cachedSVGDocument() const { return m_document.get(); }
-    CachedDocument* load(ResourceFetcher*);
+    DocumentResource* cachedSVGDocument() const { return m_document.get(); }
+    DocumentResource* load(ResourceFetcher*);
 
     String customCssText() const;
     const String& url() const { return m_url; }
@@ -50,7 +50,7 @@
     CSSSVGDocumentValue(const String& url);
 
     String m_url;
-    ResourcePtr<CachedDocument> m_document;
+    ResourcePtr<DocumentResource> m_document;
     bool m_loadRequested;
 };
 
diff --git a/Source/core/css/CSSSelector.cpp b/Source/core/css/CSSSelector.cpp
index 4fea65d..df2a968 100644
--- a/Source/core/css/CSSSelector.cpp
+++ b/Source/core/css/CSSSelector.cpp
@@ -250,6 +250,7 @@
     case PseudoPart:
     case PseudoUnresolved:
     case PseudoContent:
+    case PseudoHost:
         return NOPSEUDO;
     case PseudoNotParsed:
         ASSERT_NOT_REACHED();
@@ -331,6 +332,7 @@
     DEFINE_STATIC_LOCAL(AtomicString, fullScreenDocument, ("-webkit-full-screen-document", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, fullScreenAncestor, ("-webkit-full-screen-ancestor", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, cue, ("cue(", AtomicString::ConstructFromLiteral));
+    DEFINE_STATIC_LOCAL(AtomicString, cueWithoutParen, ("cue", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, futureCue, ("future", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, pastCue, ("past", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, seamlessDocument, ("-webkit-seamless-document", AtomicString::ConstructFromLiteral));
@@ -341,6 +343,8 @@
     DEFINE_STATIC_LOCAL(AtomicString, part, ("part(", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, unresolved, ("unresolved", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, content, ("content", AtomicString::ConstructFromLiteral));
+    DEFINE_STATIC_LOCAL(AtomicString, host, ("host", AtomicString::ConstructFromLiteral));
+    DEFINE_STATIC_LOCAL(AtomicString, hostWithParams, ("host(", AtomicString::ConstructFromLiteral));
 
     static HashMap<StringImpl*, CSSSelector::PseudoType>* nameToPseudoType = 0;
     if (!nameToPseudoType) {
@@ -414,18 +418,21 @@
         nameToPseudoType->set(fullScreenDocument.impl(), CSSSelector::PseudoFullScreenDocument);
         nameToPseudoType->set(fullScreenAncestor.impl(), CSSSelector::PseudoFullScreenAncestor);
         nameToPseudoType->set(cue.impl(), CSSSelector::PseudoCue);
+        nameToPseudoType->set(cueWithoutParen.impl(), CSSSelector::PseudoWebKitCustomElement);
         nameToPseudoType->set(futureCue.impl(), CSSSelector::PseudoFutureCue);
         nameToPseudoType->set(pastCue.impl(), CSSSelector::PseudoPastCue);
         nameToPseudoType->set(seamlessDocument.impl(), CSSSelector::PseudoSeamlessDocument);
         nameToPseudoType->set(distributed.impl(), CSSSelector::PseudoDistributed);
         nameToPseudoType->set(inRange.impl(), CSSSelector::PseudoInRange);
         nameToPseudoType->set(outOfRange.impl(), CSSSelector::PseudoOutOfRange);
-        if (RuntimeEnabledFeatures::shadowDOMEnabled())
+        if (RuntimeEnabledFeatures::shadowDOMEnabled()) {
             nameToPseudoType->set(part.impl(), CSSSelector::PseudoPart);
+            nameToPseudoType->set(host.impl(), CSSSelector::PseudoHost);
+            nameToPseudoType->set(hostWithParams.impl(), CSSSelector::PseudoHost);
+            nameToPseudoType->set(content.impl(), CSSSelector::PseudoContent);
+        }
         if (RuntimeEnabledFeatures::customDOMElementsEnabled())
             nameToPseudoType->set(unresolved.impl(), CSSSelector::PseudoUnresolved);
-        if (RuntimeEnabledFeatures::shadowDOMEnabled())
-            nameToPseudoType->set(content.impl(), CSSSelector::PseudoContent);
     }
     return nameToPseudoType;
 }
@@ -542,6 +549,7 @@
     case PseudoOutOfRange:
     case PseudoFutureCue:
     case PseudoPastCue:
+    case PseudoHost:
     case PseudoUnresolved:
         break;
     case PseudoFirstPage:
@@ -641,6 +649,18 @@
                 str.append(')');
                 break;
             }
+            case PseudoHost: {
+                if (cs->selectorList()) {
+                    const CSSSelector* firstSubSelector = cs->selectorList()->first();
+                    for (const CSSSelector* subSelector = firstSubSelector; subSelector; subSelector = CSSSelectorList::next(subSelector)) {
+                        if (subSelector != firstSubSelector)
+                            str.append(',');
+                        str.append(subSelector->selectorText());
+                    }
+                    str.append(')');
+                }
+                break;
+            }
             default:
                 break;
             }
@@ -751,6 +771,72 @@
     m_data.m_rareData->m_matchUserAgentOnly = true;
 }
 
+static bool validateSubSelector(const CSSSelector* selector)
+{
+    switch (selector->m_match) {
+    case CSSSelector::Tag:
+    case CSSSelector::Id:
+    case CSSSelector::Class:
+    case CSSSelector::Exact:
+    case CSSSelector::Set:
+    case CSSSelector::List:
+    case CSSSelector::Hyphen:
+    case CSSSelector::Contain:
+    case CSSSelector::Begin:
+    case CSSSelector::End:
+        return true;
+    case CSSSelector::PseudoElement:
+        return false;
+    case CSSSelector::PagePseudoClass:
+    case CSSSelector::PseudoClass:
+        break;
+    }
+
+    switch (selector->pseudoType()) {
+    case CSSSelector::PseudoEmpty:
+    case CSSSelector::PseudoLink:
+    case CSSSelector::PseudoVisited:
+    case CSSSelector::PseudoTarget:
+    case CSSSelector::PseudoEnabled:
+    case CSSSelector::PseudoDisabled:
+    case CSSSelector::PseudoChecked:
+    case CSSSelector::PseudoIndeterminate:
+    case CSSSelector::PseudoNthChild:
+    case CSSSelector::PseudoNthLastChild:
+    case CSSSelector::PseudoNthOfType:
+    case CSSSelector::PseudoNthLastOfType:
+    case CSSSelector::PseudoFirstChild:
+    case CSSSelector::PseudoLastChild:
+    case CSSSelector::PseudoFirstOfType:
+    case CSSSelector::PseudoLastOfType:
+    case CSSSelector::PseudoOnlyOfType:
+        return true;
+    default:
+        return false;
+    }
+}
+
+bool CSSSelector::isCompound() const
+{
+    if (!validateSubSelector(this))
+        return false;
+
+    const CSSSelector* prevSubSelector = this;
+    const CSSSelector* subSelector = tagHistory();
+
+    while (subSelector) {
+        if (prevSubSelector->relation() != CSSSelector::SubSelector)
+            return false;
+        if (!validateSubSelector(subSelector))
+            return false;
+
+        prevSubSelector = subSelector;
+        subSelector = subSelector->tagHistory();
+    }
+
+    return true;
+}
+
 bool CSSSelector::parseNth() const
 {
     if (!m_hasRareData)
diff --git a/Source/core/css/CSSSelector.h b/Source/core/css/CSSSelector.h
index 32ee1f5..028e512 100644
--- a/Source/core/css/CSSSelector.h
+++ b/Source/core/css/CSSSelector.h
@@ -162,7 +162,8 @@
             PseudoDistributed,
             PseudoPart,
             PseudoUnresolved,
-            PseudoContent
+            PseudoContent,
+            PseudoHost
         };
 
         enum MarginBoxType {
@@ -229,7 +230,8 @@
         bool isLastInTagHistory() const { return m_isLastInTagHistory; }
         void setNotLastInTagHistory() { m_isLastInTagHistory = false; }
 
-        bool isSimple() const;
+        // http://dev.w3.org/csswg/selectors4/#compound
+        bool isCompound() const;
 
         bool isForPage() const { return m_isForPage; }
         void setForPage() { m_isForPage = true; }
diff --git a/Source/core/css/CSSShaderValue.cpp b/Source/core/css/CSSShaderValue.cpp
index 7377be9..a21af14 100644
--- a/Source/core/css/CSSShaderValue.cpp
+++ b/Source/core/css/CSSShaderValue.cpp
@@ -36,7 +36,7 @@
 #include "core/dom/Document.h"
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/ResourceFetcher.h"
-#include "core/rendering/style/StyleCachedShader.h"
+#include "core/rendering/style/StyleFetchedShader.h"
 #include "core/rendering/style/StylePendingShader.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -58,7 +58,7 @@
     return loader->document()->completeURL(m_url);
 }
 
-StyleCachedShader* CSSShaderValue::cachedShader(ResourceFetcher* loader)
+StyleFetchedShader* CSSShaderValue::resource(ResourceFetcher* loader)
 {
     ASSERT(loader);
 
@@ -66,11 +66,11 @@
         m_accessedShader = true;
 
         FetchRequest request(ResourceRequest(completeURL(loader)), FetchInitiatorTypeNames::css);
-        if (ResourcePtr<CachedShader> cachedShader = loader->requestShader(request))
-            m_shader = StyleCachedShader::create(cachedShader.get());
+        if (ResourcePtr<ShaderResource> resource = loader->requestShader(request))
+            m_shader = StyleFetchedShader::create(resource.get());
     }
 
-    return (m_shader && m_shader->isCachedShader()) ? static_cast<StyleCachedShader*>(m_shader.get()) : 0;
+    return (m_shader && m_shader->isShaderResource()) ? static_cast<StyleFetchedShader*>(m_shader.get()) : 0;
 }
 
 StyleShader* CSSShaderValue::cachedOrPendingShader()
diff --git a/Source/core/css/CSSShaderValue.h b/Source/core/css/CSSShaderValue.h
index ac4e088..69daf55 100644
--- a/Source/core/css/CSSShaderValue.h
+++ b/Source/core/css/CSSShaderValue.h
@@ -36,7 +36,7 @@
 
 class ResourceFetcher;
 class KURL;
-class StyleCachedShader;
+class StyleFetchedShader;
 class StyleShader;
 
 class CSSShaderValue : public CSSValue {
@@ -48,7 +48,7 @@
     void setFormat(const String& format) { m_format = format; }
 
     KURL completeURL(ResourceFetcher*) const;
-    StyleCachedShader* cachedShader(ResourceFetcher*);
+    StyleFetchedShader* resource(ResourceFetcher*);
     StyleShader* cachedOrPendingShader();
 
     String customCssText() const;
diff --git a/Source/core/css/CSSStyleSheet.h b/Source/core/css/CSSStyleSheet.h
index 83b4f9d..f81fdef 100644
--- a/Source/core/css/CSSStyleSheet.h
+++ b/Source/core/css/CSSStyleSheet.h
@@ -34,7 +34,7 @@
 class CSSRule;
 class CSSRuleList;
 class CSSStyleSheet;
-class CachedCSSStyleSheet;
+class CSSStyleSheetResource;
 class Document;
 class ExceptionState;
 class MediaQuerySet;
diff --git a/Source/core/css/ElementRuleCollector.cpp b/Source/core/css/ElementRuleCollector.cpp
index 20ac3a3..7fbeb61 100644
--- a/Source/core/css/ElementRuleCollector.cpp
+++ b/Source/core/css/ElementRuleCollector.cpp
@@ -35,6 +35,7 @@
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/rendering/RenderRegion.h"
 
 namespace WebCore {
@@ -64,11 +65,11 @@
     return m_ruleList.release();
 }
 
-inline void ElementRuleCollector::addMatchedRule(const RuleData* rule, TreePosition treePosition)
+inline void ElementRuleCollector::addMatchedRule(const RuleData* rule, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
 {
     if (!m_matchedRules)
         m_matchedRules = adoptPtr(new Vector<MatchedRule, 32>);
-    m_matchedRules->append(MatchedRule(rule, treePosition));
+    m_matchedRules->append(MatchedRule(rule, cascadeScope, cascadeOrder));
 }
 
 void ElementRuleCollector::clearMatchedRules()
@@ -97,50 +98,68 @@
         m_result.isCacheable = false;
 }
 
-void ElementRuleCollector::collectMatchingRules(const MatchRequest& matchRequest, RuleRange& ruleRange, TreePosition treePosition)
+static bool rulesApplicableInCurrentTreeScope(const Element* element, const ContainerNode* scopingNode, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary, bool elementApplyAuthorStyles)
+{
+    TreeScope* treeScope = element->treeScope();
+
+    // [skipped, because already checked] a) it's a UA rule
+    // b) element is allowed to apply author rules
+    if (elementApplyAuthorStyles)
+        return true;
+    // c) the rules comes from a scoped style sheet within the same tree scope
+    if (!scopingNode || treeScope == scopingNode->treeScope())
+        return true;
+    // d) the rules comes from a scoped style sheet within an active shadow root whose host is the given element
+    if (element->isInShadowTree() && (behaviorAtBoundary & SelectorChecker::ScopeIsShadowHost) && scopingNode == element->containingShadowRoot()->host())
+        return true;
+    // e) the rules can cross boundaries
+    if ((behaviorAtBoundary & SelectorChecker::BoundaryBehaviorMask) == SelectorChecker::CrossesBoundary)
+        return true;
+    return false;
+}
+
+void ElementRuleCollector::collectMatchingRules(const MatchRequest& matchRequest, RuleRange& ruleRange, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
 {
     ASSERT(matchRequest.ruleSet);
     ASSERT(m_context.element());
 
     Element* element = m_context.element();
-    // FIXME: pseudo should be deprecated after all pseudo is replaced with ::part.
-    const AtomicString& pseudoId = !element->shadowPseudoId().isEmpty() ? element->shadowPseudoId() : element->shadowPartId();
+    const AtomicString& pseudoId = element->shadowPseudoId();
     if (!pseudoId.isEmpty()) {
         ASSERT(element->isStyledElement());
-        collectMatchingRulesForList(matchRequest.ruleSet->shadowPseudoElementRules(pseudoId.impl()), treePosition, matchRequest, ruleRange);
+        collectMatchingRulesForList(matchRequest.ruleSet->shadowPseudoElementRules(pseudoId.impl()), cascadeScope, cascadeOrder, matchRequest, ruleRange);
     }
 
     if (element->isWebVTTElement())
-        collectMatchingRulesForList(matchRequest.ruleSet->cuePseudoRules(), treePosition, matchRequest, ruleRange);
+        collectMatchingRulesForList(matchRequest.ruleSet->cuePseudoRules(), cascadeScope, cascadeOrder, matchRequest, ruleRange);
     // Check whether other types of rules are applicable in the current tree scope. Criteria for this:
     // a) it's a UA rule
     // b) the tree scope allows author rules
     // c) the rules comes from a scoped style sheet within the same tree scope
-    TreeScope* treeScope = element->treeScope();
-    if (!m_matchingUARules
-        && !treeScope->applyAuthorStyles()
-        && (!matchRequest.scope || matchRequest.scope->treeScope() != treeScope)
-        && (m_behaviorAtBoundary & SelectorChecker::BoundaryBehaviorMask) == SelectorChecker::DoesNotCrossBoundary)
+    // d) the rules comes from a scoped style sheet within an active shadow root whose host is the given element
+    // e) the rules can cross boundaries
+    // b)-e) is checked in rulesApplicableInCurrentTreeScope.
+    if (!m_matchingUARules && !rulesApplicableInCurrentTreeScope(element, matchRequest.scope, m_behaviorAtBoundary, matchRequest.elementApplyAuthorStyles))
         return;
 
     // We need to collect the rules for id, class, tag, and everything else into a buffer and
     // then sort the buffer.
     if (element->hasID())
-        collectMatchingRulesForList(matchRequest.ruleSet->idRules(element->idForStyleResolution().impl()), treePosition, matchRequest, ruleRange);
+        collectMatchingRulesForList(matchRequest.ruleSet->idRules(element->idForStyleResolution().impl()), cascadeScope, cascadeOrder, matchRequest, ruleRange);
     if (element->isStyledElement() && element->hasClass()) {
         for (size_t i = 0; i < element->classNames().size(); ++i)
-            collectMatchingRulesForList(matchRequest.ruleSet->classRules(element->classNames()[i].impl()), treePosition, matchRequest, ruleRange);
+            collectMatchingRulesForList(matchRequest.ruleSet->classRules(element->classNames()[i].impl()), cascadeScope, cascadeOrder, matchRequest, ruleRange);
     }
 
     if (element->isLink())
-        collectMatchingRulesForList(matchRequest.ruleSet->linkPseudoClassRules(), treePosition, matchRequest, ruleRange);
+        collectMatchingRulesForList(matchRequest.ruleSet->linkPseudoClassRules(), cascadeScope, cascadeOrder, matchRequest, ruleRange);
     if (SelectorChecker::matchesFocusPseudoClass(element))
-        collectMatchingRulesForList(matchRequest.ruleSet->focusPseudoClassRules(), treePosition, matchRequest, ruleRange);
-    collectMatchingRulesForList(matchRequest.ruleSet->tagRules(element->localName().impl()), treePosition, matchRequest, ruleRange);
-    collectMatchingRulesForList(matchRequest.ruleSet->universalRules(), treePosition, matchRequest, ruleRange);
+        collectMatchingRulesForList(matchRequest.ruleSet->focusPseudoClassRules(), cascadeScope, cascadeOrder, matchRequest, ruleRange);
+    collectMatchingRulesForList(matchRequest.ruleSet->tagRules(element->localName().impl()), cascadeScope, cascadeOrder, matchRequest, ruleRange);
+    collectMatchingRulesForList(matchRequest.ruleSet->universalRules(), cascadeScope, cascadeOrder, matchRequest, ruleRange);
 }
 
-void ElementRuleCollector::collectMatchingRulesForRegion(const MatchRequest& matchRequest, RuleRange& ruleRange, TreePosition treePosition)
+void ElementRuleCollector::collectMatchingRulesForRegion(const MatchRequest& matchRequest, RuleRange& ruleRange, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
 {
     if (!m_regionForStyling)
         return;
@@ -151,7 +170,7 @@
         if (checkRegionSelector(regionSelector, toElement(m_regionForStyling->node()))) {
             RuleSet* regionRules = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
             ASSERT(regionRules);
-            collectMatchingRules(MatchRequest(regionRules, matchRequest.includeEmptyRules, matchRequest.scope), ruleRange, treePosition);
+            collectMatchingRules(MatchRequest(regionRules, matchRequest.includeEmptyRules, matchRequest.scope), ruleRange, cascadeScope, cascadeOrder);
         }
     }
 }
@@ -218,7 +237,7 @@
     return true;
 }
 
-void ElementRuleCollector::collectRuleIfMatches(const RuleData& ruleData, TreePosition treePosition, const MatchRequest& matchRequest, RuleRange& ruleRange)
+void ElementRuleCollector::collectRuleIfMatches(const RuleData& ruleData, CascadeScope cascadeScope, CascadeOrder cascadeOrder, const MatchRequest& matchRequest, RuleRange& ruleRange)
 {
     if (m_canUseFastReject && m_selectorFilter.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
         return;
@@ -248,35 +267,37 @@
                 ruleRange.firstRuleIndex = ruleRange.lastRuleIndex;
 
             // Add this rule to our list of matched rules.
-            addMatchedRule(&ruleData, treePosition);
+            addMatchedRule(&ruleData, cascadeScope, cascadeOrder);
             return;
         }
     }
 }
 
-void ElementRuleCollector::collectMatchingRulesForList(const RuleData* rules, TreePosition treePosition, const MatchRequest& matchRequest, RuleRange& ruleRange)
+void ElementRuleCollector::collectMatchingRulesForList(const RuleData* rules, CascadeScope cascadeScope, CascadeOrder cascadeOrder, const MatchRequest& matchRequest, RuleRange& ruleRange)
 {
     if (!rules)
         return;
     while (!rules->isLastInArray())
-        collectRuleIfMatches(*rules++, treePosition, matchRequest, ruleRange);
-    collectRuleIfMatches(*rules, treePosition, matchRequest, ruleRange);
+        collectRuleIfMatches(*rules++, cascadeScope, cascadeOrder, matchRequest, ruleRange);
+    collectRuleIfMatches(*rules, cascadeScope, cascadeOrder, matchRequest, ruleRange);
 }
 
-void ElementRuleCollector::collectMatchingRulesForList(const Vector<RuleData>* rules, TreePosition treePosition, const MatchRequest& matchRequest, RuleRange& ruleRange)
+void ElementRuleCollector::collectMatchingRulesForList(const Vector<RuleData>* rules, CascadeScope cascadeScope, CascadeOrder cascadeOrder, const MatchRequest& matchRequest, RuleRange& ruleRange)
 {
     if (!rules)
         return;
     unsigned size = rules->size();
     for (unsigned i = 0; i < size; ++i)
-        collectRuleIfMatches(rules->at(i), treePosition, matchRequest, ruleRange);
+        collectRuleIfMatches(rules->at(i), cascadeScope, cascadeOrder, matchRequest, ruleRange);
 }
 
 static inline bool compareRules(const MatchedRule& matchedRule1, const MatchedRule& matchedRule2)
 {
     unsigned specificity1 = matchedRule1.ruleData()->specificity();
     unsigned specificity2 = matchedRule2.ruleData()->specificity();
-    return (specificity1 == specificity2) ? matchedRule1.globalPosition() < matchedRule2.globalPosition() : specificity1 < specificity2;
+    return matchedRule1.cascadeScope() == matchedRule2.cascadeScope() ?
+        ((specificity1 == specificity2) ? matchedRule1.position() < matchedRule2.position() : specificity1 < specificity2) :
+        matchedRule1.cascadeScope() < matchedRule2.cascadeScope();
 }
 
 void ElementRuleCollector::sortMatchedRules()
@@ -296,7 +317,7 @@
     m_behaviorAtBoundary = SelectorChecker::StaysWithinTreeScope;
     int firstRuleIndex = -1, lastRuleIndex = -1;
     RuleRange ruleRange(firstRuleIndex, lastRuleIndex);
-    // FIXME: Verify whether it's ok to ignore TreePosition here.
+    // FIXME: Verify whether it's ok to ignore CascadeScope here.
     collectMatchingRules(MatchRequest(ruleSet), ruleRange);
 
     return m_matchedRules && !m_matchedRules->isEmpty();
diff --git a/Source/core/css/ElementRuleCollector.h b/Source/core/css/ElementRuleCollector.h
index 8f08828..c52aa21 100644
--- a/Source/core/css/ElementRuleCollector.h
+++ b/Source/core/css/ElementRuleCollector.h
@@ -41,27 +41,32 @@
 class SelectorFilter;
 class StaticCSSRuleList;
 
-typedef unsigned TreePosition;
+typedef unsigned CascadeScope;
+typedef unsigned CascadeOrder;
 
-const TreePosition ignoreTreePosition = 0;
+const CascadeScope ignoreCascadeScope = 0;
+const CascadeOrder ignoreCascadeOrder = 0;
 
 class MatchedRule {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit MatchedRule(const RuleData* ruleData, TreePosition treePosition)
+    explicit MatchedRule(const RuleData* ruleData, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
         : m_ruleData(ruleData)
+        , m_cascadeScope(cascadeScope)
     {
         ASSERT(m_ruleData);
         static const unsigned BitsForPositionInRuleData = 18;
-        m_globalPosition = (treePosition << BitsForPositionInRuleData) + m_ruleData->position();
+        m_position = (cascadeOrder << BitsForPositionInRuleData) + m_ruleData->position();
     }
 
     const RuleData* ruleData() const { return m_ruleData; }
-    uint32_t globalPosition() const { return m_globalPosition; }
+    uint32_t cascadeScope() const { return m_cascadeScope; }
+    uint32_t position() const { return m_position; }
 
 private:
     const RuleData* m_ruleData;
-    uint32_t m_globalPosition;
+    CascadeScope m_cascadeScope;
+    uint32_t m_position;
 };
 
 // ElementRuleCollector is designed to be used as a stack object.
@@ -89,23 +94,26 @@
     MatchResult& matchedResult();
     PassRefPtr<CSSRuleList> matchedRuleList();
 
-    void collectMatchingRules(const MatchRequest&, RuleRange&, TreePosition = ignoreTreePosition);
-    void collectMatchingRulesForRegion(const MatchRequest&, RuleRange&, TreePosition = ignoreTreePosition);
+    void collectMatchingRules(const MatchRequest&, RuleRange&, CascadeScope = ignoreCascadeScope, CascadeOrder = ignoreCascadeOrder);
+    void collectMatchingRulesForRegion(const MatchRequest&, RuleRange&, CascadeScope = ignoreCascadeScope, CascadeOrder = ignoreCascadeOrder);
     void sortAndTransferMatchedRules();
     void clearMatchedRules();
     void addElementStyleProperties(const StylePropertySet*, bool isCacheable = true);
 
+    unsigned lastMatchedRulesPosition() const { return m_matchedRules ? m_matchedRules->size() : 0; }
+    void sortMatchedRulesFrom(unsigned position);
+    void sortAndTransferMatchedRulesWithOnlySortBySpecificity();
+
 private:
     Document* document() { return m_context.document(); }
 
-    void collectRuleIfMatches(const RuleData&, TreePosition, const MatchRequest&, RuleRange&);
-    void collectMatchingRulesForList(const Vector<RuleData>*, TreePosition, const MatchRequest&, RuleRange&);
-    void collectMatchingRulesForList(const RuleData*, TreePosition, const MatchRequest&, RuleRange&);
+    void collectRuleIfMatches(const RuleData&, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
+    void collectMatchingRulesForList(const Vector<RuleData>*, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
+    void collectMatchingRulesForList(const RuleData*, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
     bool ruleMatches(const RuleData&, const ContainerNode* scope, PseudoId&);
 
     void sortMatchedRules();
-
-    void addMatchedRule(const RuleData*, TreePosition);
+    void addMatchedRule(const RuleData*, CascadeScope, CascadeOrder);
 
     StaticCSSRuleList* ensureRuleList();
 
diff --git a/Source/core/css/FontLoader.h b/Source/core/css/FontLoader.h
index a5914d6..cd296ed 100644
--- a/Source/core/css/FontLoader.h
+++ b/Source/core/css/FontLoader.h
@@ -38,7 +38,7 @@
 
 namespace WebCore {
 
-class CachedFont;
+class FontResource;
 class CSSFontFaceRule;
 class CSSFontFaceSource;
 class Dictionary;
diff --git a/Source/core/css/FontLoader.idl b/Source/core/css/FontLoader.idl
index 4e922c1..06ce8c0 100644
--- a/Source/core/css/FontLoader.idl
+++ b/Source/core/css/FontLoader.idl
@@ -35,11 +35,11 @@
     GenerateIsReachable=document
 ] interface FontLoader : EventTarget {
 
-    attribute EventListener onloading;
-    attribute EventListener onloadingdone;
-    attribute EventListener onloadstart;
-    attribute EventListener onload;
-    attribute EventListener onerror;
+    attribute EventHandler onloading;
+    attribute EventHandler onloadingdone;
+    attribute EventHandler onloadstart;
+    attribute EventHandler onload;
+    attribute EventHandler onerror;
 
     boolean checkFont(DOMString font, [Default=NullString] optional DOMString text);
     void loadFont(Dictionary params);
diff --git a/Source/core/css/MediaList.cpp b/Source/core/css/MediaList.cpp
index fd60ac5..d2a1750 100644
--- a/Source/core/css/MediaList.cpp
+++ b/Source/core/css/MediaList.cpp
@@ -234,11 +234,11 @@
     ASSERT(document);
     ASSERT(value);
 
-    DEFINE_STATIC_LOCAL(String, mediaQueryMessage, (ASCIILiteral("Consider using 'dppx' units instead of '%replacementUnits%', as in CSS '%replacementUnits%' means dots-per-CSS-%lengthUnit%, not dots-per-physical-%lengthUnit%, so does not correspond to the actual '%replacementUnits%' of a screen. In media query expression: ")));
-    DEFINE_STATIC_LOCAL(String, mediaValueDPI, (ASCIILiteral("dpi")));
-    DEFINE_STATIC_LOCAL(String, mediaValueDPCM, (ASCIILiteral("dpcm")));
-    DEFINE_STATIC_LOCAL(String, lengthUnitInch, (ASCIILiteral("inch")));
-    DEFINE_STATIC_LOCAL(String, lengthUnitCentimeter, (ASCIILiteral("centimeter")));
+    DEFINE_STATIC_LOCAL(String, mediaQueryMessage, ("Consider using 'dppx' units instead of '%replacementUnits%', as in CSS '%replacementUnits%' means dots-per-CSS-%lengthUnit%, not dots-per-physical-%lengthUnit%, so does not correspond to the actual '%replacementUnits%' of a screen. In media query expression: "));
+    DEFINE_STATIC_LOCAL(String, mediaValueDPI, ("dpi"));
+    DEFINE_STATIC_LOCAL(String, mediaValueDPCM, ("dpcm"));
+    DEFINE_STATIC_LOCAL(String, lengthUnitInch, ("inch"));
+    DEFINE_STATIC_LOCAL(String, lengthUnitCentimeter, ("centimeter"));
 
     String message;
     if (value->isDotsPerInch())
diff --git a/Source/core/css/MediaQueryEvaluator.cpp b/Source/core/css/MediaQueryEvaluator.cpp
index 900a627..413c80e 100644
--- a/Source/core/css/MediaQueryEvaluator.cpp
+++ b/Source/core/css/MediaQueryEvaluator.cpp
@@ -337,7 +337,7 @@
     return false;
 }
 
-static bool computeLength(CSSValue* value, bool strict, RenderStyle* style, RenderStyle* rootStyle, int& result)
+static bool computeLength(CSSValue* value, bool strict, RenderStyle* initialStyle, int& result)
 {
     if (!value->isPrimitiveValue())
         return false;
@@ -350,7 +350,9 @@
     }
 
     if (primitiveValue->isLength()) {
-        result = primitiveValue->computeLength<int>(style, rootStyle, 1.0 /* multiplier */, true /* computingFontSize */);
+        // Relative (like EM) and root relative (like REM) units are always resolved against the initial values
+        // for media queries, hence the two initialStyle parameters.
+        result = primitiveValue->computeLength<int>(initialStyle, initialStyle, 1.0 /* multiplier */, true /* computingFontSize */);
         return true;
     }
 
@@ -361,11 +363,10 @@
 {
     if (value) {
         FloatRect sg = screenRect(frame->page()->mainFrame()->view());
-        RenderStyle* rootStyle = frame->document()->documentElement()->renderStyle();
         int length;
         long height = sg.height();
         InspectorInstrumentation::applyScreenHeightOverride(frame, &height);
-        return computeLength(value, !frame->document()->inQuirksMode(), style, rootStyle, length) && compareValue(static_cast<int>(height), length, op);
+        return computeLength(value, !frame->document()->inQuirksMode(), style, length) && compareValue(static_cast<int>(height), length, op);
     }
     // ({,min-,max-}device-height)
     // assume if we have a device, assume non-zero
@@ -376,11 +377,10 @@
 {
     if (value) {
         FloatRect sg = screenRect(frame->page()->mainFrame()->view());
-        RenderStyle* rootStyle = frame->document()->documentElement()->renderStyle();
         int length;
         long width = sg.width();
         InspectorInstrumentation::applyScreenWidthOverride(frame, &width);
-        return computeLength(value, !frame->document()->inQuirksMode(), style, rootStyle, length) && compareValue(static_cast<int>(width), length, op);
+        return computeLength(value, !frame->document()->inQuirksMode(), style, length) && compareValue(static_cast<int>(width), length, op);
     }
     // ({,min-,max-}device-width)
     // assume if we have a device, assume non-zero
@@ -395,9 +395,8 @@
     if (value) {
         if (RenderView* renderView = frame->document()->renderView())
             height = adjustForAbsoluteZoom(height, renderView);
-        RenderStyle* rootStyle = frame->document()->documentElement()->renderStyle();
         int length;
-        return computeLength(value, !frame->document()->inQuirksMode(), style, rootStyle, length) && compareValue(height, length, op);
+        return computeLength(value, !frame->document()->inQuirksMode(), style, length) && compareValue(height, length, op);
     }
 
     return height;
@@ -411,9 +410,8 @@
     if (value) {
         if (RenderView* renderView = frame->document()->renderView())
             width = adjustForAbsoluteZoom(width, renderView);
-        RenderStyle* rootStyle = frame->document()->documentElement()->renderStyle();
         int length;
-        return computeLength(value, !frame->document()->inQuirksMode(), style, rootStyle, length) && compareValue(width, length, op);
+        return computeLength(value, !frame->document()->inQuirksMode(), style, length) && compareValue(width, length, op);
     }
 
     return width;
diff --git a/Source/core/css/RuleFeature.cpp b/Source/core/css/RuleFeature.cpp
index 0db8234..1c187a3 100644
--- a/Source/core/css/RuleFeature.cpp
+++ b/Source/core/css/RuleFeature.cpp
@@ -31,6 +31,7 @@
 
 #include "HTMLNames.h"
 #include "core/css/CSSSelector.h"
+#include "core/css/CSSSelectorList.h"
 
 namespace WebCore {
 
@@ -53,11 +54,25 @@
     case CSSSelector::PseudoPart:
         attrsInRules.add(HTMLNames::partAttr.localName().impl());
         break;
+    case CSSSelector::PseudoHost:
+        collectFeaturesFromSelectorList(selector->selectorList());
+        break;
     default:
         break;
     }
 }
 
+void RuleFeatureSet::collectFeaturesFromSelectorList(const CSSSelectorList* selectorList)
+{
+    if (!selectorList)
+        return;
+
+    for (const CSSSelector* selector = selectorList->first(); selector; selector = CSSSelectorList::next(selector)) {
+        for (const CSSSelector* subSelector = selector; subSelector; subSelector = subSelector->tagHistory())
+            collectFeaturesFromSelector(subSelector);
+    }
+}
+
 void RuleFeatureSet::add(const RuleFeatureSet& other)
 {
     HashSet<AtomicString>::const_iterator end = other.idsInRules.end();
diff --git a/Source/core/css/RuleFeature.h b/Source/core/css/RuleFeature.h
index ed7f0d7..c9fe119 100644
--- a/Source/core/css/RuleFeature.h
+++ b/Source/core/css/RuleFeature.h
@@ -30,6 +30,7 @@
 
 class StyleRule;
 class CSSSelector;
+class CSSSelectorList;
 
 struct RuleFeature {
     RuleFeature(StyleRule* rule, unsigned selectorIndex, bool hasDocumentSecurityOrigin)
@@ -83,6 +84,8 @@
     Vector<RuleFeature> siblingRules;
     Vector<RuleFeature> uncommonAttributeRules;
 private:
+    void collectFeaturesFromSelectorList(const CSSSelectorList*);
+
     bool m_usesFirstLineRules;
     bool m_usesBeforeAfterRules;
 };
diff --git a/Source/core/css/SelectorChecker.cpp b/Source/core/css/SelectorChecker.cpp
index 03d9571..7940f7b 100644
--- a/Source/core/css/SelectorChecker.cpp
+++ b/Source/core/css/SelectorChecker.cpp
@@ -77,20 +77,57 @@
         return false;
 
     if (selector->pseudoType() != CSSSelector::PseudoPart) {
-        if (element->shadowPseudoId() != selector->value())
+        const AtomicString& pseudoId = selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement ? element->shadowPseudoId() : element->pseudo();
+        if (pseudoId != selector->value())
             return false;
         if (selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement && root->type() != ShadowRoot::UserAgentShadowRoot)
             return false;
         return true;
     }
 
-    if (element->shadowPartId() != selector->argument())
+    if (element->part() != selector->argument())
         return false;
     if (selector->isMatchUserAgentOnly() && root->type() != ShadowRoot::UserAgentShadowRoot)
         return false;
     return true;
 }
 
+Element* SelectorChecker::parentElement(const SelectorCheckingContext& context) const
+{
+    // CrossesBoundary means we don't care any context.scope. So we can walk up from a shadow root to its shadow host.
+    if ((context.behaviorAtBoundary & SelectorChecker::BoundaryBehaviorMask) == SelectorChecker::CrossesBoundary)
+        return context.element->parentOrShadowHostElement();
+
+    // If context.scope is not a shadow host, we cannot walk up from a shadow root to its shadow host.
+    if (!(context.behaviorAtBoundary & SelectorChecker::ScopeIsShadowHost))
+        return context.element->parentElement();
+
+    // If behaviorAtBoundary is StaysWithInTreeScope, we cannot walk up from a shadow root to its shadow host.
+    return (context.behaviorAtBoundary & SelectorChecker::BoundaryBehaviorMask) != SelectorChecker::StaysWithinTreeScope ? context.element->parentOrShadowHostElement() : context.element->parentElement();
+}
+
+bool SelectorChecker::scopeContainsLastMatchedElement(const SelectorCheckingContext& context) const
+{
+    if (!(context.behaviorAtBoundary & SelectorChecker::ScopeContainsLastMatchedElement))
+        return true;
+
+    ASSERT(context.scope);
+    // If behaviorAtBoundary is not ScopeIsShadowHost, we can use "contains".
+    if (!(context.behaviorAtBoundary & SelectorChecker::ScopeIsShadowHost))
+        return context.scope->contains(context.element);
+
+    // If a given element is scope, i.e. shadow host, matches.
+    if (context.element == context.scope)
+        return true;
+
+    ShadowRoot* root = context.element->containingShadowRoot();
+    if (!root)
+        return false;
+
+    // If a host of the containing shadow root is scope, matches.
+    return root->host() == context.scope;
+}
+
 // Recursive check of selectors and combinators
 // It can return 4 different values:
 // * SelectorMatches          - the selector matches the element e
@@ -130,13 +167,8 @@
 
     // Prepare next selector
     const CSSSelector* historySelector = context.selector->tagHistory();
-    if (!historySelector) {
-        if (context.behaviorAtBoundary & ScopeContainsLastMatchedElement) {
-            ASSERT(context.scope);
-            return context.scope->contains(context.element) ? SelectorMatches : SelectorFailsLocally;
-        }
-        return SelectorMatches;
-    }
+    if (!historySelector)
+        return scopeContainsLastMatchedElement(context) ? SelectorMatches : SelectorFailsLocally;
 
     SelectorCheckingContext nextContext(context);
     nextContext.selector = historySelector;
@@ -167,10 +199,9 @@
             }
             return SelectorFailsCompletely;
         }
-        nextContext.element = context.element->parentElement();
         nextContext.isSubSelector = false;
         nextContext.elementStyle = 0;
-        for (; nextContext.element; nextContext.element = nextContext.element->parentElement()) {
+        for (nextContext.element = parentElement(context); nextContext.element; nextContext.element = parentElement(nextContext)) {
             Match match = this->match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
             if (match == SelectorMatches || match == SelectorFailsCompletely)
                 return match;
@@ -179,18 +210,22 @@
         }
         return SelectorFailsCompletely;
     case CSSSelector::Child:
-        if (context.selector->relationIsAffectedByPseudoContent())
-            return matchForShadowDistributed(context.element, siblingTraversalStrategy, ignoreDynamicPseudo, nextContext);
-        nextContext.element = context.element->parentElement();
-        if (!nextContext.element)
-            return SelectorFailsCompletely;
-        nextContext.isSubSelector = false;
-        nextContext.elementStyle = 0;
-        return match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+        {
+            if (context.selector->relationIsAffectedByPseudoContent())
+                return matchForShadowDistributed(context.element, siblingTraversalStrategy, ignoreDynamicPseudo, nextContext);
+
+            nextContext.element = parentElement(context);
+            if (!nextContext.element)
+                return SelectorFailsCompletely;
+
+            nextContext.isSubSelector = false;
+            nextContext.elementStyle = 0;
+            return match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+        }
     case CSSSelector::DirectAdjacent:
         if (m_mode == ResolvingStyle) {
-            if (Element* parentElement = context.element->parentElement())
-                parentElement->setChildrenAffectedByDirectAdjacentRules();
+            if (Element* parent = parentElement(context))
+                parent->setChildrenAffectedByDirectAdjacentRules();
         }
         nextContext.element = context.element->previousElementSibling();
         if (!nextContext.element)
@@ -201,8 +236,8 @@
 
     case CSSSelector::IndirectAdjacent:
         if (m_mode == ResolvingStyle) {
-            if (Element* parentElement = context.element->parentElement())
-                parentElement->setChildrenAffectedByForwardPositionalRules();
+            if (Element* parent = parentElement(context))
+                parent->setChildrenAffectedByForwardPositionalRules();
         }
         nextContext.element = context.element->previousElementSibling();
         nextContext.isSubSelector = false;
@@ -405,7 +440,7 @@
             return checkScrollbarPseudoClass(context, element->document(), selector);
         } else if (context.hasSelectionPseudo) {
             if (selector->pseudoType() == CSSSelector::PseudoWindowInactive)
-                return !element->document()->page()->focusController()->isActive();
+                return !element->document()->page()->focusController().isActive();
         }
 
         // Normal element pseudo class checking.
@@ -440,11 +475,11 @@
             }
         case CSSSelector::PseudoFirstChild:
             // first-child matches the first child that is an element
-            if (Element* parentElement = element->parentElement()) {
+            if (Element* parent = element->parentElement()) {
                 bool result = siblingTraversalStrategy.isFirstChild(element);
                 if (m_mode == ResolvingStyle) {
                     RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle();
-                    parentElement->setChildrenAffectedByFirstChildRules();
+                    parent->setChildrenAffectedByFirstChildRules();
                     if (result && childStyle)
                         childStyle->setFirstChildState();
                 }
@@ -453,20 +488,20 @@
             break;
         case CSSSelector::PseudoFirstOfType:
             // first-of-type matches the first element of its type
-            if (Element* parentElement = element->parentElement()) {
+            if (Element* parent = element->parentElement()) {
                 bool result = siblingTraversalStrategy.isFirstOfType(element, element->tagQName());
                 if (m_mode == ResolvingStyle)
-                    parentElement->setChildrenAffectedByForwardPositionalRules();
+                    parent->setChildrenAffectedByForwardPositionalRules();
                 return result;
             }
             break;
         case CSSSelector::PseudoLastChild:
             // last-child matches the last child that is an element
-            if (Element* parentElement = element->parentElement()) {
-                bool result = parentElement->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element);
+            if (Element* parent = element->parentElement()) {
+                bool result = parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element);
                 if (m_mode == ResolvingStyle) {
                     RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle();
-                    parentElement->setChildrenAffectedByLastChildRules();
+                    parent->setChildrenAffectedByLastChildRules();
                     if (result && childStyle)
                         childStyle->setLastChildState();
                 }
@@ -475,22 +510,22 @@
             break;
         case CSSSelector::PseudoLastOfType:
             // last-of-type matches the last element of its type
-            if (Element* parentElement = element->parentElement()) {
+            if (Element* parent = element->parentElement()) {
                 if (m_mode == ResolvingStyle)
-                    parentElement->setChildrenAffectedByBackwardPositionalRules();
-                if (!parentElement->isFinishedParsingChildren())
+                    parent->setChildrenAffectedByBackwardPositionalRules();
+                if (!parent->isFinishedParsingChildren())
                     return false;
                 return siblingTraversalStrategy.isLastOfType(element, element->tagQName());
             }
             break;
         case CSSSelector::PseudoOnlyChild:
-            if (Element* parentElement = element->parentElement()) {
+            if (Element* parent = element->parentElement()) {
                 bool firstChild = siblingTraversalStrategy.isFirstChild(element);
-                bool onlyChild = firstChild && parentElement->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element);
+                bool onlyChild = firstChild && parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element);
                 if (m_mode == ResolvingStyle) {
                     RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle();
-                    parentElement->setChildrenAffectedByFirstChildRules();
-                    parentElement->setChildrenAffectedByLastChildRules();
+                    parent->setChildrenAffectedByFirstChildRules();
+                    parent->setChildrenAffectedByLastChildRules();
                     if (firstChild && childStyle)
                         childStyle->setFirstChildState();
                     if (onlyChild && childStyle)
@@ -501,12 +536,12 @@
             break;
         case CSSSelector::PseudoOnlyOfType:
             // FIXME: This selector is very slow.
-            if (Element* parentElement = element->parentElement()) {
+            if (Element* parent = element->parentElement()) {
                 if (m_mode == ResolvingStyle) {
-                    parentElement->setChildrenAffectedByForwardPositionalRules();
-                    parentElement->setChildrenAffectedByBackwardPositionalRules();
+                    parent->setChildrenAffectedByForwardPositionalRules();
+                    parent->setChildrenAffectedByBackwardPositionalRules();
                 }
-                if (!parentElement->isFinishedParsingChildren())
+                if (!parent->isFinishedParsingChildren())
                     return false;
                 return siblingTraversalStrategy.isFirstOfType(element, element->tagQName()) && siblingTraversalStrategy.isLastOfType(element, element->tagQName());
             }
@@ -514,14 +549,14 @@
         case CSSSelector::PseudoNthChild:
             if (!selector->parseNth())
                 break;
-            if (Element* parentElement = element->parentElement()) {
+            if (Element* parent = element->parentElement()) {
                 int count = 1 + siblingTraversalStrategy.countElementsBefore(element);
                 if (m_mode == ResolvingStyle) {
                     RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle();
                     element->setChildIndex(count);
                     if (childStyle)
                         childStyle->setUnique();
-                    parentElement->setChildrenAffectedByForwardPositionalRules();
+                    parent->setChildrenAffectedByForwardPositionalRules();
                 }
 
                 if (selector->matchNth(count))
@@ -531,10 +566,10 @@
         case CSSSelector::PseudoNthOfType:
             if (!selector->parseNth())
                 break;
-            if (Element* parentElement = element->parentElement()) {
+            if (Element* parent = element->parentElement()) {
                 int count = 1 + siblingTraversalStrategy.countElementsOfTypeBefore(element, element->tagQName());
                 if (m_mode == ResolvingStyle)
-                    parentElement->setChildrenAffectedByForwardPositionalRules();
+                    parent->setChildrenAffectedByForwardPositionalRules();
 
                 if (selector->matchNth(count))
                     return true;
@@ -543,10 +578,10 @@
         case CSSSelector::PseudoNthLastChild:
             if (!selector->parseNth())
                 break;
-            if (Element* parentElement = element->parentElement()) {
+            if (Element* parent = element->parentElement()) {
                 if (m_mode == ResolvingStyle)
-                    parentElement->setChildrenAffectedByBackwardPositionalRules();
-                if (!parentElement->isFinishedParsingChildren())
+                    parent->setChildrenAffectedByBackwardPositionalRules();
+                if (!parent->isFinishedParsingChildren())
                     return false;
                 int count = 1 + siblingTraversalStrategy.countElementsAfter(element);
                 if (selector->matchNth(count))
@@ -556,10 +591,10 @@
         case CSSSelector::PseudoNthLastOfType:
             if (!selector->parseNth())
                 break;
-            if (Element* parentElement = element->parentElement()) {
+            if (Element* parent = element->parentElement()) {
                 if (m_mode == ResolvingStyle)
-                    parentElement->setChildrenAffectedByBackwardPositionalRules();
-                if (!parentElement->isFinishedParsingChildren())
+                    parent->setChildrenAffectedByBackwardPositionalRules();
+                if (!parent->isFinishedParsingChildren())
                     return false;
 
                 int count = 1 + siblingTraversalStrategy.countElementsOfTypeAfter(element, element->tagQName());
@@ -756,6 +791,34 @@
                 return true;
             break;
 
+        case CSSSelector::PseudoHost:
+            {
+                // :host only matches a shadow host when :host is in a shadow tree of the shadow host.
+                if (!context.scope || !(context.behaviorAtBoundary & ScopeIsShadowHost) || context.scope != element)
+                    return false;
+                ASSERT(element->shadow());
+
+                // For empty parameter case, i.e. just :host or :host().
+                if (!selector->selectorList())
+                    return true;
+
+                SelectorCheckingContext subContext(context);
+                subContext.isSubSelector = true;
+                subContext.behaviorAtBoundary = CrossesBoundary;
+                subContext.scope = 0;
+                // Use NodeRenderingTraversal to traverse a composed ancestor list of a given element.
+                for (Element* nextElement = NodeRenderingTraversal::parentElement(element); nextElement; nextElement = NodeRenderingTraversal::parentElement(nextElement)) {
+                    // If one of simple selectors matches an element, returns SelectorMatches. Just "OR".
+                    for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(subContext.selector)) {
+                        PseudoId ignoreDynamicPseudo = NOPSEUDO;
+                        subContext.element = nextElement;
+                        if (match(subContext, ignoreDynamicPseudo, siblingTraversalStrategy) == SelectorMatches)
+                            return true;
+                    }
+                }
+            }
+            break;
+
         case CSSSelector::PseudoHorizontal:
         case CSSSelector::PseudoVertical:
         case CSSSelector::PseudoDecrement:
@@ -801,7 +864,7 @@
     // FIXME: This is a temporary hack for resizers and scrollbar corners. Eventually :window-inactive should become a real
     // pseudo class and just apply to everything.
     if (selector->pseudoType() == CSSSelector::PseudoWindowInactive)
-        return !document->page()->focusController()->isActive();
+        return !document->page()->focusController().isActive();
 
     if (!scrollbar)
         return false;
diff --git a/Source/core/css/SelectorChecker.h b/Source/core/css/SelectorChecker.h
index bab408e..50c7727 100644
--- a/Source/core/css/SelectorChecker.h
+++ b/Source/core/css/SelectorChecker.h
@@ -51,6 +51,7 @@
         StaysWithinTreeScope = 2,
         BoundaryBehaviorMask = 3, // 2bit for boundary behavior
         ScopeContainsLastMatchedElement = 4,
+        ScopeIsShadowHost = 8
     };
 
     struct SelectorCheckingContext {
@@ -107,6 +108,8 @@
 
 private:
     bool checkScrollbarPseudoClass(const SelectorCheckingContext&, Document*, const CSSSelector*) const;
+    Element* parentElement(const SelectorCheckingContext&) const;
+    bool scopeContainsLastMatchedElement(const SelectorCheckingContext&) const;
 
     static bool isFrameFocused(const Element*);
 
diff --git a/Source/core/css/StyleRuleImport.cpp b/Source/core/css/StyleRuleImport.cpp
index 33ea081..cf72813 100644
--- a/Source/core/css/StyleRuleImport.cpp
+++ b/Source/core/css/StyleRuleImport.cpp
@@ -25,7 +25,7 @@
 #include "FetchInitiatorTypeNames.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
+#include "core/loader/cache/CSSStyleSheetResource.h"
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/ResourceFetcher.h"
 
@@ -42,7 +42,7 @@
     , m_styleSheetClient(this)
     , m_strHref(href)
     , m_mediaQueries(media)
-    , m_cachedSheet(0)
+    , m_resource(0)
     , m_loading(false)
 {
     if (!m_mediaQueries)
@@ -53,11 +53,11 @@
 {
     if (m_styleSheet)
         m_styleSheet->clearOwnerRule();
-    if (m_cachedSheet)
-        m_cachedSheet->removeClient(&m_styleSheetClient);
+    if (m_resource)
+        m_resource->removeClient(&m_styleSheetClient);
 }
 
-void StyleRuleImport::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CachedCSSStyleSheet* cachedStyleSheet)
+void StyleRuleImport::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* cachedStyleSheet)
 {
     if (m_styleSheet)
         m_styleSheet->clearOwnerRule();
@@ -116,17 +116,17 @@
 
     FetchRequest request(ResourceRequest(absURL), FetchInitiatorTypeNames::css, m_parentStyleSheet->charset());
     if (m_parentStyleSheet->isUserStyleSheet())
-        m_cachedSheet = fetcher->requestUserCSSStyleSheet(request);
+        m_resource = fetcher->requestUserCSSStyleSheet(request);
     else
-        m_cachedSheet = fetcher->requestCSSStyleSheet(request);
-    if (m_cachedSheet) {
+        m_resource = fetcher->requestCSSStyleSheet(request);
+    if (m_resource) {
         // if the import rule is issued dynamically, the sheet may be
         // removed from the pending sheet count, so let the doc know
         // the sheet being imported is pending.
         if (m_parentStyleSheet && m_parentStyleSheet->loadCompleted() && rootSheet == m_parentStyleSheet)
             m_parentStyleSheet->startLoadingDynamicSheet();
         m_loading = true;
-        m_cachedSheet->addClient(&m_styleSheetClient);
+        m_resource->addClient(&m_styleSheetClient);
     }
 }
 
diff --git a/Source/core/css/StyleRuleImport.h b/Source/core/css/StyleRuleImport.h
index 1a906e5..40412e3 100644
--- a/Source/core/css/StyleRuleImport.h
+++ b/Source/core/css/StyleRuleImport.h
@@ -23,12 +23,12 @@
 #define StyleRuleImport_h
 
 #include "core/css/StyleRule.h"
-#include "core/loader/cache/CachedStyleSheetClient.h"
 #include "core/loader/cache/ResourcePtr.h"
+#include "core/loader/cache/StyleSheetResourceClient.h"
 
 namespace WebCore {
 
-class CachedCSSStyleSheet;
+class CSSStyleSheetResource;
 class MediaQuerySet;
 class StyleSheetContents;
 
@@ -52,13 +52,13 @@
     void requestStyleSheet();
 
 private:
-    // NOTE: We put the CachedStyleSheetClient in a member instead of inheriting from it
+    // NOTE: We put the StyleSheetResourceClient in a member instead of inheriting from it
     // to avoid adding a vptr to StyleRuleImport.
-    class ImportedStyleSheetClient : public CachedStyleSheetClient {
+    class ImportedStyleSheetClient : public StyleSheetResourceClient {
     public:
         ImportedStyleSheetClient(StyleRuleImport* ownerRule) : m_ownerRule(ownerRule) { }
         virtual ~ImportedStyleSheetClient() { }
-        virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CachedCSSStyleSheet* sheet)
+        virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* sheet)
         {
             m_ownerRule->setCSSStyleSheet(href, baseURL, charset, sheet);
         }
@@ -66,7 +66,7 @@
         StyleRuleImport* m_ownerRule;
     };
 
-    void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CachedCSSStyleSheet*);
+    void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*);
     friend class ImportedStyleSheetClient;
 
     StyleRuleImport(const String& href, PassRefPtr<MediaQuerySet>);
@@ -77,7 +77,7 @@
     String m_strHref;
     RefPtr<MediaQuerySet> m_mediaQueries;
     RefPtr<StyleSheetContents> m_styleSheet;
-    ResourcePtr<CachedCSSStyleSheet> m_cachedSheet;
+    ResourcePtr<CSSStyleSheetResource> m_resource;
     bool m_loading;
 };
 
diff --git a/Source/core/css/StyleSheetContents.cpp b/Source/core/css/StyleSheetContents.cpp
index 891fa78..163276b 100644
--- a/Source/core/css/StyleSheetContents.cpp
+++ b/Source/core/css/StyleSheetContents.cpp
@@ -28,7 +28,7 @@
 #include "core/css/StyleRule.h"
 #include "core/css/StyleRuleImport.h"
 #include "core/dom/Node.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
+#include "core/loader/cache/CSSStyleSheetResource.h"
 #include "weborigin/SecurityOrigin.h"
 #include "wtf/Deque.h"
 
@@ -269,7 +269,7 @@
     return it->value;
 }
 
-void StyleSheetContents::parseAuthorStyleSheet(const CachedCSSStyleSheet* cachedStyleSheet, const SecurityOrigin* securityOrigin)
+void StyleSheetContents::parseAuthorStyleSheet(const CSSStyleSheetResource* cachedStyleSheet, const SecurityOrigin* securityOrigin)
 {
     bool enforceMIMEType = isStrictParserMode(m_parserContext.mode);
     bool hasValidMIMEType = false;
@@ -290,7 +290,7 @@
     }
     if (m_parserContext.needsSiteSpecificQuirks && isStrictParserMode(m_parserContext.mode)) {
         // Work around <https://bugs.webkit.org/show_bug.cgi?id=28350>.
-        DEFINE_STATIC_LOCAL(const String, mediaWikiKHTMLFixesStyleSheet, (ASCIILiteral("/* KHTML fix stylesheet */\n/* work around the horizontal scrollbars */\n#column-content { margin-left: 0; }\n\n")));
+        DEFINE_STATIC_LOCAL(const String, mediaWikiKHTMLFixesStyleSheet, ("/* KHTML fix stylesheet */\n/* work around the horizontal scrollbars */\n#column-content { margin-left: 0; }\n\n"));
         // There are two variants of KHTMLFixes.css. One is equal to mediaWikiKHTMLFixesStyleSheet,
         // while the other lacks the second trailing newline.
         if (baseURL().string().endsWith("/KHTMLFixes.css") && !sheetText.isNull() && mediaWikiKHTMLFixesStyleSheet.startsWith(sheetText)
@@ -348,7 +348,7 @@
         ownerNode->notifyLoadedSheetAndAllCriticalSubresources(m_didLoadErrorOccur);
 }
 
-void StyleSheetContents::notifyLoadedSheet(const CachedCSSStyleSheet* sheet)
+void StyleSheetContents::notifyLoadedSheet(const CSSStyleSheetResource* sheet)
 {
     ASSERT(sheet);
     m_didLoadErrorOccur |= sheet->errorOccurred();
diff --git a/Source/core/css/StyleSheetContents.h b/Source/core/css/StyleSheetContents.h
index ee0c872..02bf850 100644
--- a/Source/core/css/StyleSheetContents.h
+++ b/Source/core/css/StyleSheetContents.h
@@ -34,7 +34,7 @@
 namespace WebCore {
 
 class CSSStyleSheet;
-class CachedCSSStyleSheet;
+class CSSStyleSheetResource;
 class Document;
 class Node;
 class SecurityOrigin;
@@ -62,7 +62,7 @@
 
     const AtomicString& determineNamespace(const AtomicString& prefix);
 
-    void parseAuthorStyleSheet(const CachedCSSStyleSheet*, const SecurityOrigin*);
+    void parseAuthorStyleSheet(const CSSStyleSheetResource*, const SecurityOrigin*);
     bool parseString(const String&);
     bool parseStringAtPosition(const String&, const TextPosition&, bool);
 
@@ -104,7 +104,7 @@
     const Vector<RefPtr<StyleRuleBase> >& childRules() const { return m_childRules; }
     const Vector<RefPtr<StyleRuleImport> >& importRules() const { return m_importRules; }
 
-    void notifyLoadedSheet(const CachedCSSStyleSheet*);
+    void notifyLoadedSheet(const CSSStyleSheetResource*);
 
     StyleSheetContents* parentStyleSheet() const;
     StyleRuleImport* ownerRule() const { return m_ownerRule; }
diff --git a/Source/core/css/resolver/AnimatedStyleBuilder.cpp b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
new file mode 100644
index 0000000..8fc9535
--- /dev/null
+++ b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/resolver/AnimatedStyleBuilder.h"
+
+#include "core/animation/AnimatableNumber.h"
+#include "core/animation/AnimatableUnknown.h"
+#include "core/animation/AnimatableValue.h"
+#include "core/css/resolver/StyleBuilder.h"
+#include "core/css/resolver/StyleResolverState.h"
+#include "core/rendering/style/RenderStyle.h"
+
+namespace WebCore {
+
+namespace {
+
+Length animatableValueToLength(const AnimatableValue* value, const StyleResolverState& state)
+{
+    const RenderStyle* style = state.style();
+    return toAnimatableNumber(value)->toLength(style, state.rootElementStyle(), style->effectiveZoom());
+}
+
+} // namespace
+
+// FIXME: This should handle all animatable properties
+//   (see CSSAnimatableValueFactory for list of remaining)
+
+// FIXME: Generate this function.
+void AnimatedStyleBuilder::applyProperty(CSSPropertyID property, StyleResolverState& state, const AnimatableValue* value)
+{
+    if (value->isUnknown()) {
+        StyleBuilder::applyProperty(property, state, toAnimatableUnknown(value)->toCSSValue().get());
+        return;
+    }
+    RenderStyle* style = state.style();
+    switch (property) {
+    case CSSPropertyBottom:
+        style->setBottom(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyHeight:
+        style->setHeight(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyLeft:
+        style->setLeft(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyMarginBottom:
+        style->setMarginBottom(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyMarginLeft:
+        style->setMarginLeft(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyMarginRight:
+        style->setMarginRight(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyMarginTop:
+        style->setMarginTop(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyMaxHeight:
+        style->setMaxHeight(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyMaxWidth:
+        style->setMaxWidth(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyMinHeight:
+        style->setMinHeight(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyMinWidth:
+        style->setMinWidth(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyOpacity:
+        style->setOpacity(toAnimatableNumber(value)->toDouble());
+        return;
+    case CSSPropertyPaddingBottom:
+        style->setPaddingBottom(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyPaddingLeft:
+        style->setPaddingLeft(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyPaddingRight:
+        style->setPaddingRight(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyPaddingTop:
+        style->setPaddingTop(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyRight:
+        style->setRight(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyTop:
+        style->setTop(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyWebkitPerspectiveOriginX:
+        style->setPerspectiveOriginX(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyWebkitPerspectiveOriginY:
+        style->setPerspectiveOriginY(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyWebkitTransformOriginX:
+        style->setTransformOriginX(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyWebkitTransformOriginY:
+        style->setTransformOriginY(animatableValueToLength(value, state));
+        return;
+    case CSSPropertyWidth:
+        style->setWidth(animatableValueToLength(value, state));
+        return;
+    default:
+        RELEASE_ASSERT_WITH_MESSAGE(false, "Unable to apply AnimatableValue to RenderStyle, not yet implemented!");
+        return;
+    }
+}
+
+} // namespace WebCore
diff --git a/Source/core/platform/chromium/DragDataRef.h b/Source/core/css/resolver/AnimatedStyleBuilder.h
similarity index 80%
copy from Source/core/platform/chromium/DragDataRef.h
copy to Source/core/css/resolver/AnimatedStyleBuilder.h
index 7df3554..3f91a14 100644
--- a/Source/core/platform/chromium/DragDataRef.h
+++ b/Source/core/css/resolver/AnimatedStyleBuilder.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,15 +28,21 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef DragDataRef_h
-#define DragDataRef_h
+#ifndef AnimatedStyleBuilder_h
+#define AnimatedStyleBuilder_h
 
-#include "core/platform/chromium/ChromiumDataObject.h"
+#include "CSSPropertyNames.h"
 
 namespace WebCore {
 
-    typedef ChromiumDataObject* DragDataRef;
+class AnimatableValue;
+class StyleResolverState;
+
+class AnimatedStyleBuilder {
+public:
+    static void applyProperty(CSSPropertyID, StyleResolverState&, const AnimatableValue*);
+};
 
 } // namespace WebCore
 
-#endif
+#endif // AnimatedStyleBuilder_h
diff --git a/Source/core/css/resolver/FilterOperationResolver.cpp b/Source/core/css/resolver/FilterOperationResolver.cpp
index 3198f67..a409394 100644
--- a/Source/core/css/resolver/FilterOperationResolver.cpp
+++ b/Source/core/css/resolver/FilterOperationResolver.cpp
@@ -409,7 +409,7 @@
                 if (!svgDocumentValue->loadRequested())
                     state.elementStyleResources().addPendingSVGDocument(operation.get(), svgDocumentValue);
                 else if (svgDocumentValue->cachedSVGDocument())
-                    operation->setCachedSVGDocumentReference(adoptPtr(new CachedSVGDocumentReference(svgDocumentValue->cachedSVGDocument())));
+                    operation->setDocumentResourceReference(adoptPtr(new DocumentResourceReference(svgDocumentValue->cachedSVGDocument())));
             }
             operations.operations().append(operation);
             continue;
diff --git a/Source/core/css/resolver/MatchRequest.h b/Source/core/css/resolver/MatchRequest.h
index 2986361..8b120d4 100644
--- a/Source/core/css/resolver/MatchRequest.h
+++ b/Source/core/css/resolver/MatchRequest.h
@@ -31,10 +31,11 @@
 
 class MatchRequest {
 public:
-    MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0)
+    MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0, bool elementApplyAuthorStyles = true)
         : ruleSet(ruleSet)
         , includeEmptyRules(includeEmptyRules)
         , scope(scope)
+        , elementApplyAuthorStyles(elementApplyAuthorStyles)
     {
         // Now that we're about to read from the RuleSet, we're done adding more
         // rules to the set and we should make sure it's compacted.
@@ -44,6 +45,7 @@
     const RuleSet* ruleSet;
     const bool includeEmptyRules;
     const ContainerNode* scope;
+    const bool elementApplyAuthorStyles;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/ScopedStyleResolver.cpp b/Source/core/css/resolver/ScopedStyleResolver.cpp
index 70419be..1100570 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -29,7 +29,6 @@
 
 #include "HTMLNames.h"
 #include "core/css/CSSStyleSheet.h"
-#include "core/css/ElementRuleCollector.h"
 #include "core/css/PageRuleCollector.h"
 #include "core/css/RuleFeature.h"
 #include "core/css/RuleSet.h"
@@ -126,6 +125,23 @@
         resolvers.append(scopedResolver);
 }
 
+void ScopedStyleTree::collectScopedResolversForHostedShadowTrees(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
+{
+    ElementShadow* shadow = element->shadow();
+    if (!shadow)
+        return;
+
+    // Adding scoped resolver for active shadow roots for shadow host styling.
+    for (ShadowRoot* shadowRoot = shadow->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
+        if (shadowRoot->hasScopedHTMLStyleChild()) {
+            if (ScopedStyleResolver* resolver = scopedStyleResolverFor(shadowRoot))
+                resolvers.append(resolver);
+        }
+        if (!shadowRoot->containsShadowElements())
+            break;
+    }
+}
+
 void ScopedStyleTree::resolveScopedKeyframesRules(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
 {
     Document* document = element->document();
@@ -310,8 +326,6 @@
     if (m_keyframesRuleMap.isEmpty())
         return 0;
 
-    m_keyframesRuleMap.checkConsistency();
-
     KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(animationName);
     if (it == m_keyframesRuleMap.end())
         return 0;
@@ -334,7 +348,7 @@
 void ScopedStyleResolver::matchHostRules(ElementRuleCollector& collector, bool includeEmptyRules)
 {
     // FIXME: Determine tree position.
-    TreePosition treePosition = ignoreTreePosition;
+    CascadeScope cascadeScope = ignoreCascadeScope;
 
     if (m_atHostRules.isEmpty() || !m_scopingNode->isElementNode())
         return;
@@ -362,7 +376,7 @@
     collector.setBehaviorAtBoundary(static_cast<SelectorChecker::BehaviorAtBoundary>(SelectorChecker::DoesNotCrossBoundary | SelectorChecker::ScopeContainsLastMatchedElement));
     for (; shadowRoot; shadowRoot = shadowRoot->youngerShadowRoot()) {
         if (RuleSet* ruleSet = atHostRuleSetFor(shadowRoot))
-            collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, m_scopingNode), ruleRange, treePosition);
+            collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, m_scopingNode), ruleRange, cascadeScope);
     }
 
     collector.sortAndTransferMatchedRules();
@@ -370,21 +384,33 @@
 
 void ScopedStyleResolver::matchAuthorRules(ElementRuleCollector& collector, bool includeEmptyRules, bool applyAuthorStyles)
 {
-    // FIXME: Determine tree position.
-    TreePosition treePosition = ignoreTreePosition;
+    collector.clearMatchedRules();
+    collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
+    collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, ignoreCascadeScope);
+    collector.sortAndTransferMatchedRules();
+}
 
-    if (m_authorStyle) {
-        collector.clearMatchedRules();
-        collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
+void ScopedStyleResolver::collectMatchingAuthorRules(ElementRuleCollector& collector, bool includeEmptyRules, bool applyAuthorStyles, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
+{
+    if (!m_authorStyle)
+        return;
 
-        // Match author rules.
-        MatchRequest matchRequest(m_authorStyle.get(), includeEmptyRules, m_scopingNode);
-        RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
-        collector.setBehaviorAtBoundary(applyAuthorStyles ? SelectorChecker::DoesNotCrossBoundary : static_cast<SelectorChecker::BehaviorAtBoundary>(SelectorChecker::DoesNotCrossBoundary | SelectorChecker::ScopeContainsLastMatchedElement));
-        collector.collectMatchingRules(matchRequest, ruleRange, treePosition);
-        collector.collectMatchingRulesForRegion(matchRequest, ruleRange, treePosition);
-        collector.sortAndTransferMatchedRules();
+    const ContainerNode* scopingNode = m_scopingNode;
+    unsigned behaviorAtBoundary = SelectorChecker::DoesNotCrossBoundary;
+
+    if (!applyAuthorStyles)
+        behaviorAtBoundary |= SelectorChecker::ScopeContainsLastMatchedElement;
+
+    if (m_scopingNode->isShadowRoot()) {
+        scopingNode = toShadowRoot(m_scopingNode)->host();
+        behaviorAtBoundary |= SelectorChecker::ScopeIsShadowHost;
     }
+
+    MatchRequest matchRequest(m_authorStyle.get(), includeEmptyRules, scopingNode, applyAuthorStyles);
+    RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
+    collector.setBehaviorAtBoundary(static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary));
+    collector.collectMatchingRules(matchRequest, ruleRange, cascadeScope, cascadeOrder);
+    collector.collectMatchingRulesForRegion(matchRequest, ruleRange, cascadeScope, cascadeOrder);
 }
 
 void ScopedStyleResolver::matchPageRules(PageRuleCollector& collector)
diff --git a/Source/core/css/resolver/ScopedStyleResolver.h b/Source/core/css/resolver/ScopedStyleResolver.h
index f63034d..fa06133 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.h
+++ b/Source/core/css/resolver/ScopedStyleResolver.h
@@ -28,6 +28,7 @@
 #define ScopedStyleResolver_h
 
 #include "core/css/CSSKeyframesRule.h"
+#include "core/css/ElementRuleCollector.h"
 #include "core/css/RuleSet.h"
 #include "core/dom/ContainerNode.h"
 #include "core/dom/Element.h"
@@ -68,6 +69,7 @@
 
     void matchHostRules(ElementRuleCollector&, bool includeEmptyRules);
     void matchAuthorRules(ElementRuleCollector&, bool includeEmptyRules, bool applyAuthorStyles);
+    void collectMatchingAuthorRules(ElementRuleCollector&, bool includeEmptyRules, bool applyAuthorStyles, CascadeScope, CascadeOrder = ignoreCascadeOrder);
     void matchPageRules(PageRuleCollector&);
     void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver*);
     void addHostRule(StyleRuleHost*, bool hasDocumentSecurityOrigin, const ContainerNode* scopingNode);
@@ -108,6 +110,7 @@
     ScopedStyleResolver* scopedStyleResolverForDocument() { return m_scopedResolverForDocument; }
 
     void resolveScopedStyles(const Element*, Vector<ScopedStyleResolver*, 8>&);
+    void collectScopedResolversForHostedShadowTrees(const Element*, Vector<ScopedStyleResolver*, 8>&);
     void resolveScopedKeyframesRules(const Element*, Vector<ScopedStyleResolver*, 8>&);
     ScopedStyleResolver* scopedResolverFor(const Element*);
 
diff --git a/Source/core/css/resolver/SharedStyleFinder.cpp b/Source/core/css/resolver/SharedStyleFinder.cpp
index bb6a759..ee83ce2 100644
--- a/Source/core/css/resolver/SharedStyleFinder.cpp
+++ b/Source/core/css/resolver/SharedStyleFinder.cpp
@@ -42,6 +42,7 @@
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/QualifiedName.h"
 #include "core/dom/SpaceSplitString.h"
+#include "core/dom/shadow/ElementShadow.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLOptGroupElement.h"
@@ -79,6 +80,8 @@
         return 0;
     if (parent->hasID() && m_features.idsInRules.contains(parent->idForStyleResolution().impl()))
         return 0;
+    if (isShadowHost(parent) && parent->shadow()->containsActiveStyles())
+        return 0;
 
     RenderStyle* parentStyle = parent->renderStyle();
     unsigned subcount = 0;
@@ -247,6 +250,8 @@
         return false;
     if (element->hasScopedHTMLStyleChild())
         return false;
+    if (isShadowHost(element) && element->shadow()->containsActiveStyles())
+        return 0;
 
     // FIXME: We should share style for option and optgroup whenever possible.
     // Before doing so, we need to resolve issues in HTMLSelectElement::recalcListItems
@@ -356,6 +361,8 @@
     // size may be different each time a dialog is opened.
     if (context.element()->hasTagName(dialogTag))
         return 0;
+    if (isShadowHost(context.element()) && context.element()->shadow()->containsActiveStyles())
+        return 0;
 
     STYLE_STATS_ADD_ELEMENT_ELIGIBLE_FOR_SHARING();
 
diff --git a/Source/core/css/resolver/StyleAdjuster.cpp b/Source/core/css/resolver/StyleAdjuster.cpp
index a3792a9..dcc4fd7 100644
--- a/Source/core/css/resolver/StyleAdjuster.cpp
+++ b/Source/core/css/resolver/StyleAdjuster.cpp
@@ -363,7 +363,7 @@
     if (e && e->hasTagName(iframeTag) && style->display() == INLINE && toHTMLIFrameElement(e)->shouldDisplaySeamlessly())
         style->setDisplay(INLINE_BLOCK);
 
-    adjustGridItemPosition(style);
+    adjustGridItemPosition(style, parentStyle);
 
     if (e && e->isSVGElement()) {
         // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
@@ -388,20 +388,35 @@
     }
 }
 
-void StyleAdjuster::adjustGridItemPosition(RenderStyle* style) const
+void StyleAdjuster::adjustGridItemPosition(RenderStyle* style, RenderStyle* parentStyle) const
 {
+    const GridPosition& columnStartPosition = style->gridColumnStart();
+    const GridPosition& columnEndPosition = style->gridColumnEnd();
+    const GridPosition& rowStartPosition = style->gridRowStart();
+    const GridPosition& rowEndPosition = style->gridRowEnd();
+
     // If opposing grid-placement properties both specify a grid span, they both compute to ‘auto’.
-    if (style->gridColumnStart().isSpan() && style->gridColumnEnd().isSpan()) {
+    if (columnStartPosition.isSpan() && columnEndPosition.isSpan()) {
         style->setGridColumnStart(GridPosition());
         style->setGridColumnEnd(GridPosition());
     }
 
-    if (style->gridRowStart().isSpan() && style->gridRowEnd().isSpan()) {
+    if (rowStartPosition.isSpan() && rowEndPosition.isSpan()) {
         style->setGridRowStart(GridPosition());
         style->setGridRowEnd(GridPosition());
     }
+
+    // Unknown named grid area compute to 'auto'.
+    const NamedGridAreaMap& map = parentStyle->namedGridArea();
+
+#define CLEAR_UNKNOWN_NAMED_AREA(prop, Prop) \
+    if (prop.isNamedGridArea() && !map.contains(prop.namedGridLine())) \
+        style->setGrid##Prop(GridPosition());
+
+    CLEAR_UNKNOWN_NAMED_AREA(columnStartPosition, ColumnStart);
+    CLEAR_UNKNOWN_NAMED_AREA(columnEndPosition, ColumnEnd);
+    CLEAR_UNKNOWN_NAMED_AREA(rowStartPosition, RowStart);
+    CLEAR_UNKNOWN_NAMED_AREA(rowEndPosition, RowEnd);
 }
 
-
-
 }
diff --git a/Source/core/css/resolver/StyleAdjuster.h b/Source/core/css/resolver/StyleAdjuster.h
index 25b9411..96e5927 100644
--- a/Source/core/css/resolver/StyleAdjuster.h
+++ b/Source/core/css/resolver/StyleAdjuster.h
@@ -41,7 +41,7 @@
     void adjustRenderStyle(RenderStyle* styleToAdjust, RenderStyle* parentStyle, Element*);
 
 private:
-    void adjustGridItemPosition(RenderStyle*) const;
+    void adjustGridItemPosition(RenderStyle*, RenderStyle*) const;
 
     const CachedUAStyle& m_cachedUAStyle;
     bool m_useQuirksModeStyles;
diff --git a/Source/core/css/resolver/StyleBuilderCustom.cpp b/Source/core/css/resolver/StyleBuilderCustom.cpp
index e9b9c65..f49afb1 100644
--- a/Source/core/css/resolver/StyleBuilderCustom.cpp
+++ b/Source/core/css/resolver/StyleBuilderCustom.cpp
@@ -37,7 +37,7 @@
  */
 
 #include "config.h"
-#include "core/css/resolver/StyleBuilder.h"
+#include "core/css/resolver/StyleBuilderCustom.h"
 
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
@@ -64,6 +64,7 @@
 #include "core/css/resolver/ElementStyleResources.h"
 #include "core/css/resolver/FilterOperationResolver.h"
 #include "core/css/resolver/FontBuilder.h"
+#include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/StyleResolverState.h"
 #include "core/css/resolver/TransformBuilder.h"
 #include "core/page/Frame.h"
@@ -823,6 +824,81 @@
 }
 #endif // CSS3_TEXT
 
+Length StyleBuilderConverter::convertLength(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    Length result = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    ASSERT(!result.isUndefined());
+    result.setQuirk(primitiveValue->isQuirkValue());
+    return result;
+}
+
+Length StyleBuilderConverter::convertLengthOrAuto(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    Length result = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | AutoConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    ASSERT(!result.isUndefined());
+    result.setQuirk(primitiveValue->isQuirkValue());
+    return result;
+}
+
+Length StyleBuilderConverter::convertLengthSizing(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    switch (primitiveValue->getValueID()) {
+    case CSSValueInvalid:
+        return convertLength(state, value);
+    case CSSValueIntrinsic:
+        return Length(Intrinsic);
+    case CSSValueMinIntrinsic:
+        return Length(MinIntrinsic);
+    case CSSValueWebkitMinContent:
+        return Length(MinContent);
+    case CSSValueWebkitMaxContent:
+        return Length(MaxContent);
+    case CSSValueWebkitFillAvailable:
+        return Length(FillAvailable);
+    case CSSValueWebkitFitContent:
+        return Length(FitContent);
+    case CSSValueAuto:
+        return Length(Auto);
+    default:
+        ASSERT_NOT_REACHED();
+        return Length();
+    }
+}
+
+Length StyleBuilderConverter::convertLengthMaxSizing(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    if (primitiveValue->getValueID() == CSSValueNone)
+        return Length(Undefined);
+    return convertLengthSizing(state, value);
+}
+
+LengthSize StyleBuilderConverter::convertRadius(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    Pair* pair = primitiveValue->getPairValue();
+    Length radiusWidth = pair->first()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    Length radiusHeight = pair->second()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+    float width = radiusWidth.value();
+    float height = radiusHeight.value();
+    ASSERT(width >= 0 && height >= 0);
+    if (width <= 0 || height <= 0)
+        return LengthSize(Length(0, Fixed), Length(0, Fixed));
+    return LengthSize(radiusWidth, radiusHeight);
+}
+
+float StyleBuilderConverter::convertSpacing(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    if (primitiveValue->getValueID() == CSSValueNormal)
+        return 0;
+    float zoom = state.useSVGZoomRules() ? 1.0f : state.style()->effectiveZoom();
+    return primitiveValue->computeLength<float>(state.style(), state.rootElementStyle(), zoom);
+}
+
 
 // Everything below this line is from the old StyleResolver::applyProperty
 // and eventually needs to move into new StyleBuilderFunctions calls intead.
diff --git a/Source/core/css/resolver/StyleBuilderCustom.h b/Source/core/css/resolver/StyleBuilderCustom.h
new file mode 100644
index 0000000..2496b3b
--- /dev/null
+++ b/Source/core/css/resolver/StyleBuilderCustom.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef StyleBuilderCustom_h
+#define StyleBuilderCustom_h
+
+#include "core/css/CSSValue.h"
+#include "core/css/resolver/StyleResolverState.h"
+#include "core/platform/LengthSize.h"
+#include "core/svg/SVGLength.h"
+
+namespace WebCore {
+
+// Note that we assume the parser only allows valid CSSValue types.
+
+class StyleBuilderConverter {
+public:
+    template <typename T> static T convertComputedLength(StyleResolverState&, CSSValue*);
+    template <typename T> static T convertLineWidth(StyleResolverState&, CSSValue*);
+    static Length convertLength(StyleResolverState&, CSSValue*);
+    static Length convertLengthOrAuto(StyleResolverState&, CSSValue*);
+    static Length convertLengthSizing(StyleResolverState&, CSSValue*);
+    static Length convertLengthMaxSizing(StyleResolverState&, CSSValue*);
+    static LengthSize convertRadius(StyleResolverState&, CSSValue*);
+    static float convertSpacing(StyleResolverState&, CSSValue*);
+    template <CSSValueID IdForNone> static AtomicString convertString(StyleResolverState&, CSSValue*);
+};
+
+template <typename T>
+T StyleBuilderConverter::convertComputedLength(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    float zoom = state.style()->effectiveZoom();
+    return primitiveValue->computeLength<T>(state.style(), state.rootElementStyle(), zoom);
+}
+
+template <typename T>
+T StyleBuilderConverter::convertLineWidth(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    CSSValueID valueID = primitiveValue->getValueID();
+    if (valueID == CSSValueThin)
+        return 1;
+    if (valueID == CSSValueMedium)
+        return 3;
+    if (valueID == CSSValueThick)
+        return 5;
+    if (valueID == CSSValueInvalid) {
+        float zoom = state.style()->effectiveZoom();
+        // Any original result that was >= 1 should not be allowed to fall below 1.
+        // This keeps border lines from vanishing.
+        T result = primitiveValue->computeLength<T>(state.style(), state.rootElementStyle(), zoom);
+        if (zoom < 1.0f && result < 1.0) {
+            T originalLength = primitiveValue->computeLength<T>(state.style(), state.rootElementStyle(), 1.0);
+            if (originalLength >= 1.0)
+                return 1.0;
+        }
+        return result;
+    }
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
+template <CSSValueID IdForNone>
+AtomicString StyleBuilderConverter::convertString(StyleResolverState&, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    if (primitiveValue->getValueID() == IdForNone)
+        return nullAtom;
+    return primitiveValue->getStringValue();
+}
+
+} // namespace WebCore
+
+#endif
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index d37e8a3..4ce361f 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -33,6 +33,7 @@
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "StylePropertyShorthand.h"
+#include "core/animation/AnimatableNumber.h"
 #include "core/animation/AnimatableValue.h"
 #include "core/animation/Animation.h"
 #include "core/animation/DocumentTimeline.h"
@@ -55,6 +56,7 @@
 #include "core/css/PageRuleCollector.h"
 #include "core/css/RuleSet.h"
 #include "core/css/StylePropertySet.h"
+#include "core/css/resolver/AnimatedStyleBuilder.h"
 #include "core/css/resolver/MatchResult.h"
 #include "core/css/resolver/MediaQueryResult.h"
 #include "core/css/resolver/SharedStyleFinder.h"
@@ -65,6 +67,8 @@
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingContext.h"
 #include "core/dom/Text.h"
+#include "core/dom/shadow/ContentDistributor.h"
+#include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
@@ -287,7 +291,7 @@
 inline void StyleResolver::matchShadowDistributedRules(ElementRuleCollector& collector, bool includeEmptyRules)
 {
     // FIXME: Determine tree position.
-    TreePosition treePosition = ignoreTreePosition;
+    CascadeScope cascadeScope = ignoreCascadeScope;
 
     if (m_ruleSets.shadowDistributedRules().isEmpty())
         return;
@@ -304,7 +308,7 @@
     Vector<MatchRequest> matchRequests;
     m_ruleSets.shadowDistributedRules().collectMatchRequests(includeEmptyRules, matchRequests);
     for (size_t i = 0; i < matchRequests.size(); ++i)
-        collector.collectMatchingRules(matchRequests[i], ruleRange, treePosition);
+        collector.collectMatchingRules(matchRequests[i], ruleRange, cascadeScope);
     collector.sortAndTransferMatchedRules();
 
     collector.setBehaviorAtBoundary(previousBoundary);
@@ -318,24 +322,63 @@
     resolver->matchHostRules(collector, includeEmptyRules);
 }
 
+static inline bool applyAuthorStylesOf(const Element* element)
+{
+    return element->treeScope()->applyAuthorStyles() || (element->shadow() && element->shadow()->applyAuthorStyles());
+}
+
+void StyleResolver::matchScopedAuthorRulesForShadowHost(Element* element, ElementRuleCollector& collector, bool includeEmptyRules, Vector<ScopedStyleResolver*, 8>& resolvers, Vector<ScopedStyleResolver*, 8>& resolversInShadowTree)
+{
+    collector.clearMatchedRules();
+    collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
+
+    CascadeScope cascadeScope = (resolvers.isEmpty() || resolvers.first()->treeScope() != element->treeScope()) ? resolvers.size() + 1 : resolvers.size();
+    CascadeOrder cascadeOrder = 0;
+    bool applyAuthorStyles = applyAuthorStylesOf(element);
+
+    for (int j = resolversInShadowTree.size() - 1; j >= 0; --j)
+        resolversInShadowTree.at(j)->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope, cascadeOrder++);
+
+    cascadeScope = resolvers.size();
+    for (unsigned i = 0; i < resolvers.size(); ++i)
+        resolvers.at(i)->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope--, cascadeOrder);
+
+    collector.sortAndTransferMatchedRules();
+
+    if (!resolvers.isEmpty())
+        matchHostRules(element, resolvers.first(), collector, includeEmptyRules);
+}
+
 void StyleResolver::matchScopedAuthorRules(Element* element, ElementRuleCollector& collector, bool includeEmptyRules)
 {
-    // fast path
     if (m_styleTree.hasOnlyScopedResolverForDocument()) {
-        m_styleTree.scopedStyleResolverForDocument()->matchAuthorRules(collector, includeEmptyRules, element->treeScope()->applyAuthorStyles());
+        m_styleTree.scopedStyleResolverForDocument()->matchAuthorRules(collector, includeEmptyRules, applyAuthorStylesOf(element));
         return;
     }
 
-    Vector<ScopedStyleResolver*, 8> stack;
-    m_styleTree.resolveScopedStyles(element, stack);
-    if (stack.isEmpty())
+    Vector<ScopedStyleResolver*, 8> resolvers;
+    m_styleTree.resolveScopedStyles(element, resolvers);
+
+    Vector<ScopedStyleResolver*, 8> resolversInShadowTree;
+    m_styleTree.collectScopedResolversForHostedShadowTrees(element, resolversInShadowTree);
+    if (!resolversInShadowTree.isEmpty()) {
+        matchScopedAuthorRulesForShadowHost(element, collector, includeEmptyRules, resolvers, resolversInShadowTree);
+        return;
+    }
+
+    if (resolvers.isEmpty())
         return;
 
-    bool applyAuthorStyles = element->treeScope()->applyAuthorStyles();
-    for (int i = stack.size() - 1; i >= 0; --i)
-        stack.at(i)->matchAuthorRules(collector, includeEmptyRules, applyAuthorStyles);
+    bool applyAuthorStyles = applyAuthorStylesOf(element);
+    CascadeScope cascadeScope = resolvers.size();
+    collector.clearMatchedRules();
+    collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
 
-    matchHostRules(element, stack.first(), collector, includeEmptyRules);
+    for (unsigned i = 0; i < resolvers.size(); ++i)
+        resolvers.at(i)->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope--);
+    collector.sortAndTransferMatchedRules();
+
+    matchHostRules(element, resolvers.first(), collector, includeEmptyRules);
 }
 
 void StyleResolver::matchAuthorRules(Element* element, ElementRuleCollector& collector, bool includeEmptyRules)
@@ -777,15 +820,17 @@
         RefPtr<RenderStyle> keyframeStyle = styleForKeyframe(element, style, styleKeyframe);
         Vector<float> offsets;
         styleKeyframe->getKeys(offsets);
+        RefPtr<Keyframe> firstOffsetKeyframe;
         for (size_t j = 0; j < offsets.size(); ++j) {
             RefPtr<Keyframe> keyframe = Keyframe::create();
             keyframe->setOffset(offsets[j]);
             const StylePropertySet* properties = styleKeyframe->properties();
-            // FIXME: AnimatableValues should be shared between the keyframes at different offsets.
             for (unsigned k = 0; k < properties->propertyCount(); k++) {
                 CSSPropertyID property = properties->propertyAt(k).id();
-                keyframe->setPropertyValue(property, CSSAnimatableValueFactory::create(property, keyframeStyle.get()).get());
+                keyframe->setPropertyValue(property, firstOffsetKeyframe ? firstOffsetKeyframe->propertyValue(property) : CSSAnimatableValueFactory::create(property, keyframeStyle.get()).get());
             }
+            if (!firstOffsetKeyframe)
+                firstOffsetKeyframe = keyframe;
             keyframes.append(keyframe);
         }
     }
@@ -794,6 +839,7 @@
         return;
 
     // Remove duplicate keyframes. In CSS the last keyframe at a given offset takes priority.
+    std::stable_sort(keyframes.begin(), keyframes.end(), Keyframe::compareOffsets);
     size_t targetIndex = 0;
     for (size_t i = 1; i < keyframes.size(); i++) {
         if (keyframes[i]->offset() != keyframes[targetIndex]->offset())
@@ -803,36 +849,43 @@
     }
     keyframes.shrink(targetIndex + 1);
 
-    bool isStartKeyframeMissing = keyframes[0]->offset();
-    bool isEndKeyframeMissing = keyframes[keyframes.size() - 1]->offset() != 1;
-    if (!isStartKeyframeMissing && !isEndKeyframeMissing)
-        return;
-
     HashSet<CSSPropertyID> allProperties;
-    for (size_t i = 0; i < styleKeyframes.size(); ++i) {
-        const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
-        Vector<float> offsets;
-        styleKeyframe->getKeys(offsets);
-        const StylePropertySet* properties = styleKeyframe->properties();
-        for (unsigned j = 0; j < properties->propertyCount(); ++j) {
-            allProperties.add(properties->propertyAt(j).id());
-        }
+    for (size_t i = 0; i < keyframes.size(); i++) {
+        const HashSet<CSSPropertyID> keyframeProperties = keyframes[i]->properties();
+        for (HashSet<CSSPropertyID>::const_iterator iter = keyframeProperties.begin(); iter != keyframeProperties.end(); ++iter)
+            allProperties.add(*iter);
     }
 
-    if (isStartKeyframeMissing) {
-        RefPtr<Keyframe> keyframe = Keyframe::create();
-        keyframe->setOffset(0);
-        for (HashSet<CSSPropertyID>::const_iterator iter = allProperties.begin(); iter != allProperties.end(); ++iter)
-            keyframe->setPropertyValue(*iter, CSSAnimatableValueFactory::create(*iter, style).get());
-        keyframes.prepend(keyframe);
+    // Snapshot current property values for 0% and 100% if missing.
+    RefPtr<Keyframe> startKeyframe = keyframes[0];
+    if (startKeyframe->offset()) {
+        startKeyframe = Keyframe::create();
+        startKeyframe->setOffset(0);
+        keyframes.prepend(startKeyframe);
     }
-
-    if (isEndKeyframeMissing) {
-        RefPtr<Keyframe> keyframe = Keyframe::create();
-        keyframe->setOffset(1);
-        for (HashSet<CSSPropertyID>::const_iterator iter = allProperties.begin(); iter != allProperties.end(); ++iter)
-            keyframe->setPropertyValue(*iter, CSSAnimatableValueFactory::create(*iter, style).get());
-        keyframes.append(keyframe);
+    RefPtr<Keyframe> endKeyframe = keyframes[keyframes.size() - 1];
+    if (endKeyframe->offset() != 1) {
+        endKeyframe = Keyframe::create();
+        endKeyframe->setOffset(1);
+        keyframes.append(endKeyframe);
+    }
+    const HashSet<CSSPropertyID>& startKeyframeProperties = startKeyframe->properties();
+    const HashSet<CSSPropertyID>& endKeyframeProperties = endKeyframe->properties();
+    bool missingStartValues = startKeyframeProperties.size() < allProperties.size();
+    bool missingEndValues = endKeyframeProperties.size() < allProperties.size();
+    if (!missingStartValues && !missingEndValues)
+        return;
+    for (HashSet<CSSPropertyID>::const_iterator iter = allProperties.begin(); iter != allProperties.end(); ++iter) {
+        const CSSPropertyID property = *iter;
+        bool startNeedsValue = missingStartValues && !startKeyframeProperties.contains(property);
+        bool endNeedsValue = missingEndValues && !endKeyframeProperties.contains(property);
+        if (!startNeedsValue && !endNeedsValue)
+            continue;
+        RefPtr<AnimatableValue> snapshotValue = CSSAnimatableValueFactory::create(property, style);
+        if (startNeedsValue)
+            startKeyframe->setPropertyValue(property, snapshotValue.get());
+        if (endNeedsValue)
+            endKeyframe->setPropertyValue(property, snapshotValue.get());
     }
 }
 
@@ -1111,11 +1164,12 @@
             CSSPropertyID property = iter->key;
             if (!isPropertyForPass<pass>(property))
                 continue;
-            RefPtr<CSSValue> value = iter->value->compositeOnto(AnimatableValue::neutralValue())->toCSSValue();
+            RELEASE_ASSERT_WITH_MESSAGE(!iter->value->dependsOnUnderlyingValue(), "Not yet implemented: An interface for compositing onto the underlying value.");
+            RefPtr<AnimatableValue> animatableValue = iter->value->compositeOnto(0);
             if (pass == HighPriorityProperties && property == CSSPropertyLineHeight)
-                state.setLineHeightValue(value.get());
+                state.setLineHeightValue(toAnimatableNumber(animatableValue.get())->toCSSValue().get());
             else
-                StyleBuilder::applyProperty(property, state, value.get());
+                AnimatedStyleBuilder::applyProperty(property, state, animatableValue.get());
         }
     }
 }
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index ccb9540..d9d14e9 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -286,6 +286,7 @@
     void matchUARules(ElementRuleCollector&, RuleSet*);
     void matchAuthorRules(Element*, ElementRuleCollector&, bool includeEmptyRules);
     void matchShadowDistributedRules(ElementRuleCollector&, bool includeEmptyRules);
+    void matchScopedAuthorRulesForShadowHost(Element*, ElementRuleCollector&, bool includeEmptyRules, Vector<ScopedStyleResolver*, 8>& resolvers, Vector<ScopedStyleResolver*, 8>& resolversInShadowTree);
     void matchHostRules(Element*, ScopedStyleResolver*, ElementRuleCollector&, bool includeEmptyRules);
     void matchScopedAuthorRules(Element*, ElementRuleCollector&, bool includeEmptyRules);
     void matchAllRules(StyleResolverState&, ElementRuleCollector&, bool matchAuthorAndUserStyles, bool includeSMILProperties);
diff --git a/Source/core/css/resolver/StyleResourceLoader.cpp b/Source/core/css/resolver/StyleResourceLoader.cpp
index c649be4..bec0985 100644
--- a/Source/core/css/resolver/StyleResourceLoader.cpp
+++ b/Source/core/css/resolver/StyleResourceLoader.cpp
@@ -35,11 +35,11 @@
 #include "core/rendering/style/CursorList.h"
 #include "core/rendering/style/FillLayer.h"
 #include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/StyleCachedImage.h"
-#include "core/rendering/style/StyleCachedImageSet.h"
-#include "core/rendering/style/StyleCachedShader.h"
 #include "core/rendering/style/StyleCustomFilterProgram.h"
 #include "core/rendering/style/StyleCustomFilterProgramCache.h"
+#include "core/rendering/style/StyleFetchedImage.h"
+#include "core/rendering/style/StyleFetchedImageSet.h"
+#include "core/rendering/style/StyleFetchedShader.h"
 #include "core/rendering/style/StyleGeneratedImage.h"
 #include "core/rendering/style/StylePendingImage.h"
 #include "core/rendering/style/StylePendingShader.h"
@@ -66,12 +66,12 @@
             CSSSVGDocumentValue* value = elementStyleResources.pendingSVGDocuments().get(referenceFilter);
             if (!value)
                 continue;
-            CachedDocument* cachedDocument = value->load(m_fetcher);
-            if (!cachedDocument)
+            DocumentResource* resource = value->load(m_fetcher);
+            if (!resource)
                 continue;
 
-            // Stash the CachedDocument on the reference filter.
-            referenceFilter->setCachedSVGDocumentReference(adoptPtr(new CachedSVGDocumentReference(cachedDocument)));
+            // Stash the DocumentResource on the reference filter.
+            referenceFilter->setDocumentResourceReference(adoptPtr(new DocumentResourceReference(resource)));
         }
     }
 }
@@ -218,7 +218,7 @@
             CustomFilterOperation* customFilter = static_cast<CustomFilterOperation*>(filterOperation.get());
             ASSERT(customFilter->program());
             StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customFilter->program());
-            // Note that the StylePendingShaders could be already resolved to StyleCachedShaders. That's because the rule was matched before.
+            // Note that the StylePendingShaders could be already resolved to StyleFetchedShaders. That's because the rule was matched before.
             // However, the StyleCustomFilterProgram that was initially created could have been removed from the cache in the meanwhile,
             // meaning that we get a new StyleCustomFilterProgram here that is not yet in the cache, but already has loaded StyleShaders.
             if (!program->hasPendingShaders() && program->inCache())
@@ -229,11 +229,11 @@
             } else {
                 if (program->vertexShader() && program->vertexShader()->isPendingShader()) {
                     CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->vertexShader())->cssShaderValue();
-                    program->setVertexShader(shaderValue->cachedShader(m_fetcher));
+                    program->setVertexShader(shaderValue->resource(m_fetcher));
                 }
                 if (program->fragmentShader() && program->fragmentShader()->isPendingShader()) {
                     CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->fragmentShader())->cssShaderValue();
-                    program->setFragmentShader(shaderValue->cachedShader(m_fetcher));
+                    program->setFragmentShader(shaderValue->resource(m_fetcher));
                 }
                 m_customFilterProgramCache->add(program);
             }
diff --git a/Source/core/dom/Attr.idl b/Source/core/dom/Attr.idl
index de9d951..97c7c46 100644
--- a/Source/core/dom/Attr.idl
+++ b/Source/core/dom/Attr.idl
@@ -26,7 +26,7 @@
 
     readonly attribute boolean specified;
 
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString value;
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException, CustomElementCallbacks=Enable] attribute DOMString value;
 
     // DOM Level 2
 
diff --git a/Source/core/dom/CheckedRadioButtons.cpp b/Source/core/dom/CheckedRadioButtons.cpp
index d8d7a46..0dc3b4d 100644
--- a/Source/core/dom/CheckedRadioButtons.cpp
+++ b/Source/core/dom/CheckedRadioButtons.cpp
@@ -228,7 +228,6 @@
 {
     if (!m_nameToGroupMap)
         return 0;
-    m_nameToGroupMap->checkConsistency();
     RadioButtonGroup* group = m_nameToGroupMap->get(name.impl());
     return group ? group->checkedButton() : 0;
 }
@@ -252,7 +251,6 @@
     if (!m_nameToGroupMap)
         return;
 
-    m_nameToGroupMap->checkConsistency();
     NameToGroupMap::iterator it = m_nameToGroupMap->find(element->name().impl());
     if (it == m_nameToGroupMap->end())
         return;
diff --git a/Source/core/dom/ChildNode.idl b/Source/core/dom/ChildNode.idl
index d320e11..8a0be4d 100644
--- a/Source/core/dom/ChildNode.idl
+++ b/Source/core/dom/ChildNode.idl
@@ -26,6 +26,6 @@
 ] interface ChildNode {
     [PerWorldBindings] readonly attribute Element previousElementSibling;
     [PerWorldBindings] readonly attribute Element nextElementSibling;
-    [RaisesException, DeliverCustomElementCallbacks] void remove();
+    [RaisesException, CustomElementCallbacks=Enable] void remove();
 };
 
diff --git a/Source/core/dom/Clipboard.cpp b/Source/core/dom/Clipboard.cpp
index 694d750..0c7f725 100644
--- a/Source/core/dom/Clipboard.cpp
+++ b/Source/core/dom/Clipboard.cpp
@@ -27,7 +27,7 @@
 #include "core/dom/Clipboard.h"
 
 #include "core/fileapi/FileList.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Clipboard.h b/Source/core/dom/Clipboard.h
index 10cafc6..a32134b 100644
--- a/Source/core/dom/Clipboard.h
+++ b/Source/core/dom/Clipboard.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class CachedImage;
+class ImageResource;
 class DataTransferItemList;
 class DragData;
 class DragImage;
@@ -75,8 +75,8 @@
     virtual PassRefPtr<FileList> files() const = 0;
 
     IntPoint dragLocation() const { return m_dragLoc; }
-    CachedImage* dragImage() const { return m_dragImage.get(); }
-    virtual void setDragImage(CachedImage*, const IntPoint&) = 0;
+    ImageResource* dragImage() const { return m_dragImage.get(); }
+    virtual void setDragImage(ImageResource*, const IntPoint&) = 0;
     Node* dragImageElement() const { return m_dragImageElement.get(); }
     virtual void setDragImageElement(Node*, const IntPoint&) = 0;
 
@@ -127,7 +127,7 @@
 
 protected:
     IntPoint m_dragLoc;
-    ResourcePtr<CachedImage> m_dragImage;
+    ResourcePtr<ImageResource> m_dragImage;
     RefPtr<Node> m_dragImageElement;
 };
 
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index fc982a9..1b26b71 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -712,6 +712,7 @@
 void ContainerNode::attach(const AttachContext& context)
 {
     attachChildren(context);
+    clearChildNeedsStyleRecalc();
     Node::attach(context);
 }
 
diff --git a/Source/core/dom/CustomElement.cpp b/Source/core/dom/CustomElement.cpp
index cc8371a..6ffcd2a 100644
--- a/Source/core/dom/CustomElement.cpp
+++ b/Source/core/dom/CustomElement.cpp
@@ -40,7 +40,7 @@
 
 namespace WebCore {
 
-Vector<AtomicString>& CustomElement::additionalCustomTagNames()
+Vector<AtomicString>& CustomElement::allowedCustomTagNames()
 {
     DEFINE_STATIC_LOCAL(Vector<AtomicString>, tagNames, ());
     return tagNames;
@@ -51,14 +51,17 @@
     AtomicString lower = localName.lower();
     if (isCustomTagName(lower))
         return;
-    additionalCustomTagNames().append(lower);
+    allowedCustomTagNames().append(lower);
 }
 
 bool CustomElement::isValidTypeName(const AtomicString& name)
 {
-    if (notFound != additionalCustomTagNames().find(name))
+    if (notFound != allowedCustomTagNames().find(name))
         return true;
 
+    if (allowedCustomTagNames().size() > 0)
+        return false;
+
     if (notFound == name.find('-'))
         return false;
 
diff --git a/Source/core/dom/CustomElement.h b/Source/core/dom/CustomElement.h
index 4acdb18..4fc4b57 100644
--- a/Source/core/dom/CustomElement.h
+++ b/Source/core/dom/CustomElement.h
@@ -70,7 +70,7 @@
 private:
     CustomElement();
 
-    static Vector<AtomicString>& additionalCustomTagNames();
+    static Vector<AtomicString>& allowedCustomTagNames();
 
     // Maps resolved elements to their definitions
 
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.cpp b/Source/core/dom/CustomElementCallbackDispatcher.cpp
index 7904e73..405d7cf 100644
--- a/Source/core/dom/CustomElementCallbackDispatcher.cpp
+++ b/Source/core/dom/CustomElementCallbackDispatcher.cpp
@@ -39,7 +39,7 @@
 size_t CustomElementCallbackDispatcher::s_elementQueueStart = 0;
 
 // The base of the stack has a null sentinel value.
-size_t CustomElementCallbackDispatcher::s_elementQueueEnd = 1;
+size_t CustomElementCallbackDispatcher::s_elementQueueEnd = kNumSentinels;
 
 CustomElementCallbackDispatcher& CustomElementCallbackDispatcher::instance()
 {
@@ -54,21 +54,27 @@
     if (inCallbackDeliveryScope())
         return false;
 
-    size_t start = 1; // skip null sentinel
+    size_t start = kNumSentinels; // skip null sentinel
     size_t end = s_elementQueueEnd;
+    ElementQueue thisQueue = currentElementQueue();
 
     for (size_t i = start; i < end; i++) {
-        m_flattenedProcessingStack[i]->processInElementQueue(currentElementQueue());
+        {
+            // The created callback may schedule entered document
+            // callbacks.
+            CallbackDeliveryScope deliveryScope;
+            m_flattenedProcessingStack[i]->processInElementQueue(thisQueue);
+        }
 
-        // new callbacks as a result of recursion must be scheduled in
-        // a CallbackDeliveryScope which restore this queue on completion
         ASSERT(!s_elementQueueStart);
         ASSERT(s_elementQueueEnd == end);
     }
 
-    s_elementQueueEnd = 1;
+    s_elementQueueEnd = kNumSentinels;
     m_flattenedProcessingStack.resize(s_elementQueueEnd);
-    m_elementCallbackQueueMap.clear();
+
+    ElementCallbackQueueMap emptyMap;
+    m_elementCallbackQueueMap.swap(emptyMap);
 
     bool didWork = start < end;
     return didWork;
@@ -83,14 +89,16 @@
 void CustomElementCallbackDispatcher::processElementQueueAndPop(size_t start, size_t end)
 {
     ASSERT(isMainThread());
+    ElementQueue thisQueue = currentElementQueue();
 
     for (size_t i = start; i < end; i++) {
-        m_flattenedProcessingStack[i]->processInElementQueue(currentElementQueue());
+        {
+            // The created callback may schedule entered document
+            // callbacks.
+            CallbackDeliveryScope deliveryScope;
+            m_flattenedProcessingStack[i]->processInElementQueue(thisQueue);
+        }
 
-        // process() may run script which grows and shrinks the
-        // processing stack above this entry, but the processing stack
-        // should always drop back to having this entry at the
-        // top-of-stack on exit
         ASSERT(start == s_elementQueueStart);
         ASSERT(end == s_elementQueueEnd);
     }
@@ -99,8 +107,10 @@
     m_flattenedProcessingStack.resize(start);
     s_elementQueueEnd = start;
 
-    if (start == /* allow sentinel */ 1)
-        m_elementCallbackQueueMap.clear();
+    if (start == kNumSentinels) {
+        ElementCallbackQueueMap emptyMap;
+        m_elementCallbackQueueMap.swap(emptyMap);
+    }
 }
 
 CustomElementCallbackQueue* CustomElementCallbackDispatcher::createCallbackQueue(PassRefPtr<Element> element)
@@ -144,7 +154,7 @@
 
     // The created callback is unique in being prepended to the front
     // of the element queue
-    m_flattenedProcessingStack.insert(inCallbackDeliveryScope() ? s_elementQueueStart : /* skip null sentinel */ 1, queue);
+    m_flattenedProcessingStack.insert(inCallbackDeliveryScope() ? s_elementQueueStart : kNumSentinels, queue);
     ++s_elementQueueEnd;
 
     return queue;
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.h b/Source/core/dom/CustomElementCallbackDispatcher.h
index 4c44910..74c0ae7 100644
--- a/Source/core/dom/CustomElementCallbackDispatcher.h
+++ b/Source/core/dom/CustomElementCallbackDispatcher.h
@@ -85,7 +85,8 @@
         // is popped when empty, this sentinel will cause a null deref
         // crash.
         CustomElementCallbackQueue* sentinel = 0;
-        m_flattenedProcessingStack.append(sentinel);
+        for (size_t i = 0; i < kNumSentinels; i++)
+            m_flattenedProcessingStack.append(sentinel);
         ASSERT(s_elementQueueEnd == m_flattenedProcessingStack.size());
     }
 
@@ -111,6 +112,7 @@
     // The processing stack, flattened. Element queues lower in the
     // stack appear toward the head of the vector. The first element
     // is a null sentinel value.
+    static const size_t kNumSentinels = 1;
     Vector<CustomElementCallbackQueue*> m_flattenedProcessingStack;
 
     typedef HashMap<Element*, OwnPtr<CustomElementCallbackQueue> > ElementCallbackQueueMap;
diff --git a/Source/core/dom/DOMException.cpp b/Source/core/dom/DOMException.cpp
index 3287698..7510e27 100644
--- a/Source/core/dom/DOMException.cpp
+++ b/Source/core/dom/DOMException.cpp
@@ -100,8 +100,8 @@
     const CoreException* entry = getErrorEntry(ec);
     ASSERT(entry);
     return adoptRef(new DOMException(entry->code,
-        ASCIILiteral(entry->name ? entry->name : "Error"),
-        message.isNull() ? String(ASCIILiteral(entry->message)) : message));
+        entry->name ? entry->name : "Error",
+        message.isNull() ? String(entry->message) : message));
 }
 
 String DOMException::toString() const
@@ -114,9 +114,9 @@
     const CoreException* entry = getErrorEntry(ec);
     ASSERT(entry);
     if (!entry)
-        return ASCIILiteral("UnknownError");
+        return "UnknownError";
 
-    return ASCIILiteral(entry->name);
+    return entry->name;
 }
 
 String DOMException::getErrorMessage(ExceptionCode ec)
@@ -124,9 +124,9 @@
     const CoreException* entry = getErrorEntry(ec);
     ASSERT(entry);
     if (!entry)
-        return ASCIILiteral("Unknown error.");
+        return "Unknown error.";
 
-    return ASCIILiteral(entry->message);
+    return entry->message;
 }
 
 unsigned short DOMException::getLegacyErrorCode(ExceptionCode ec)
diff --git a/Source/core/dom/DataTransferItem.idl b/Source/core/dom/DataTransferItem.idl
index 4ce2992..7a3327f 100644
--- a/Source/core/dom/DataTransferItem.idl
+++ b/Source/core/dom/DataTransferItem.idl
@@ -34,7 +34,7 @@
     readonly attribute DOMString kind;
     readonly attribute DOMString type;
 
-    void getAsString([Default=Undefined] optional StringCallback callback);
+    void getAsString(StringCallback? callback);
     Blob getAsFile();
 };
 
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index 3097fe7..6b1ae91 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -123,9 +123,11 @@
 #include "core/loader/CookieJar.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
+#include "core/loader/FrameLoaderClient.h"
 #include "core/loader/ImageLoader.h"
 #include "core/loader/Prerenderer.h"
 #include "core/loader/TextResourceDecoder.h"
+#include "core/loader/appcache/ApplicationCacheHost.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
@@ -408,8 +410,7 @@
     , m_markers(adoptPtr(new DocumentMarkerController))
     , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
     , m_cssTarget(0)
-    , m_processingLoadEvent(false)
-    , m_loadEventFinished(false)
+    , m_loadEventProgress(LoadEventNotRun)
     , m_startTime(currentTime())
     , m_overMinimumLayoutThreshold(false)
     , m_scriptRunner(ScriptRunner::create(this))
@@ -1057,9 +1058,9 @@
 
 String Document::readyState() const
 {
-    DEFINE_STATIC_LOCAL(const String, loading, (ASCIILiteral("loading")));
-    DEFINE_STATIC_LOCAL(const String, interactive, (ASCIILiteral("interactive")));
-    DEFINE_STATIC_LOCAL(const String, complete, (ASCIILiteral("complete")));
+    DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
+    DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
+    DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
 
     switch (m_readyState) {
     case Loading:
@@ -2083,6 +2084,8 @@
 
     if (m_frame)
         m_frame->loader()->didExplicitOpen();
+    if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
+        m_loadEventProgress = LoadEventNotRun;
 }
 
 void Document::detachParser()
@@ -2214,7 +2217,11 @@
     }
 
     bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
-    bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
+    bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
+
+    // If the load was blocked because of a pending location change and the location change triggers a same document
+    // navigation, don't fire load events after the same document navigation completes (unless there's an explicit open).
+    m_loadEventProgress = LoadEventTried;
 
     if (!doload)
         return;
@@ -2223,7 +2230,7 @@
     // attached Document) to be destroyed.
     RefPtr<DOMWindow> protect(this->domWindow());
 
-    m_processingLoadEvent = true;
+    m_loadEventProgress = LoadEventInProgress;
 
     ScriptableDocumentParser* parser = scriptableDocumentParser();
     m_wellFormed = parser && parser->wellFormed();
@@ -2255,12 +2262,14 @@
     enqueuePageshowEvent(PageshowEventNotPersisted);
     enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
 
-    if (f)
-        f->loader()->handledOnloadEvents();
+    if (frame()) {
+        frame()->loader()->client()->dispatchDidHandleOnloadEvents();
+        loader()->applicationCacheHost()->stopDeferringEvents();
+    }
 
     // An event handler may have removed the frame
     if (!frame()) {
-        m_processingLoadEvent = false;
+        m_loadEventProgress = LoadEventCompleted;
         return;
     }
 
@@ -2271,12 +2280,11 @@
     if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
         // Just bail out. Before or during the onload we were shifted to another page.
         // The old i-Bench suite does this. When this happens don't bother painting or laying out.
-        m_processingLoadEvent = false;
+        m_loadEventProgress = LoadEventCompleted;
         view()->unscheduleRelayout();
         return;
     }
 
-    frame()->loader()->checkCallImplicitClose();
     RenderObject* renderObject = renderer();
 
     // We used to force a synchronous display and flush here.  This really isn't
@@ -2291,7 +2299,7 @@
             view()->layout();
     }
 
-    m_processingLoadEvent = false;
+    m_loadEventProgress = LoadEventCompleted;
 
     if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
         // The AX cache may have been cleared at this point, but we need to make sure it contains an
@@ -2687,32 +2695,35 @@
 
 void Document::processHttpEquivRefresh(const String& content)
 {
-    Frame* frame = this->frame();
-    if (!frame)
+    maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
+}
+
+void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType httpRefreshType)
+{
+    if (m_isViewSource || !m_frame)
         return;
 
     double delay;
-    String refreshUrl;
-    if (parseHTTPRefresh(content, true, delay, refreshUrl)) {
-        if (refreshUrl.isEmpty())
-            refreshUrl = m_url.string();
-        else
-            refreshUrl = completeURL(refreshUrl).string();
+    String refreshURL;
+    if (!parseHTTPRefresh(content, httpRefreshType == HttpRefreshFromMetaTag, delay, refreshURL))
+        return;
+    if (refreshURL.isEmpty())
+        refreshURL = url().string();
+    else
+        refreshURL = completeURL(refreshURL).string();
 
-        if (protocolIsJavaScript(refreshUrl)) {
-            String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
-            addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
-            return;
-        }
-
-        if (isSandboxed(SandboxAutomaticFeatures)) {
-            String message = "Refused to execute the redirect specified via '<meta http-equiv='refresh' content='...'>'. The document is sandboxed, and the 'allow-scripts' keyword is not set.";
-            addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
-            return;
-        }
-
-        frame->navigationScheduler()->scheduleRedirect(delay, refreshUrl);
+    if (protocolIsJavaScript(refreshURL)) {
+        String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
+        addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+        return;
     }
+
+    if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
+        String message = "Refused to execute the redirect specified via '<meta http-equiv='refresh' content='...'>'. The document is sandboxed, and the 'allow-scripts' keyword is not set.";
+        addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+        return;
+    }
+    m_frame->navigationScheduler()->scheduleRedirect(delay, refreshURL);
 }
 
 void Document::processHttpEquivSetCookie(const String& content)
@@ -2971,11 +2982,31 @@
     return true;
 }
 
-PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
+PassRefPtr<Node> Document::cloneNode(bool deep)
 {
-    // Spec says cloning Document nodes is "implementation dependent"
-    // so we do not support it...
-    return 0;
+    RefPtr<Document> clone = cloneDocumentWithoutChildren();
+    clone->cloneDataFromDocument(*this);
+    if (deep)
+        cloneChildNodes(clone.get());
+    return clone.release();
+}
+
+PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
+{
+    return create();
+}
+
+void Document::cloneDataFromDocument(const Document& other)
+{
+    m_url = other.url();
+    m_baseURL = other.baseURL();
+    m_baseURLOverride = other.baseURLOverride();
+    m_documentURI = other.documentURI();
+
+    setCompatibilityMode(other.compatibilityMode());
+    setContextFeatures(other.contextFeatures());
+    setSecurityOrigin(other.securityOrigin());
+    setDecoder(other.decoder());
 }
 
 StyleSheetList* Document::styleSheets()
@@ -3488,7 +3519,6 @@
     if (!domWindow)
         return;
     domWindow->dispatchLoadEvent();
-    m_loadEventFinished = true;
 }
 
 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
@@ -3596,15 +3626,13 @@
 void Document::setDomain(const String& newDomain, ExceptionState& es)
 {
     if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
-        es.throwDOMException(SecurityError);
+        es.throwDOMException(SecurityError, "'document.domain' assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
         return;
     }
 
     // Both NS and IE specify that changing the domain is only allowed when
     // the new domain is a suffix of the old domain.
 
-    // FIXME: We should add logging indicating why a domain was not allowed.
-
     // If the new domain is the same as the old domain, still call
     // securityOrigin()->setDomainForDOM. This will change the
     // security check behavior. For example, if a page loaded on port 8000
@@ -3620,24 +3648,25 @@
 
     int oldLength = domain().length();
     int newLength = newDomain.length();
-    // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
+    String exceptionMessage =  "'document.domain' assignment failed: '" + newDomain + "' is not a suffix of '" + domain() + "'.";
+    // e.g. newDomain = subdomain.www.example.com (25) and domain() = www.example.com (15)
     if (newLength >= oldLength) {
-        es.throwDOMException(SecurityError);
+        es.throwDOMException(SecurityError, exceptionMessage);
         return;
     }
 
     String test = domain();
-    // Check that it's a subdomain, not e.g. "ebkit.org"
+    // Check that it's a complete suffix, not e.g. "ample.com"
     if (test[oldLength - newLength - 1] != '.') {
-        es.throwDOMException(SecurityError);
+        es.throwDOMException(SecurityError, exceptionMessage);
         return;
     }
 
-    // Now test is "webkit.org" from domain()
+    // Now test is "example.com" from domain()
     // and we check that it's the same thing as newDomain
     test.remove(0, oldLength - newLength);
     if (test != newDomain) {
-        es.throwDOMException(SecurityError);
+        es.throwDOMException(SecurityError, exceptionMessage);
         return;
     }
 
@@ -4326,19 +4355,6 @@
     return isMainThread();
 }
 
-void Document::updateURLForPushOrReplaceState(const KURL& url)
-{
-    Frame* f = frame();
-    if (!f)
-        return;
-
-    setURL(url);
-    f->loader()->setOutgoingReferrer(url);
-
-    if (DocumentLoader* documentLoader = loader())
-        documentLoader->replaceRequestURLForSameDocumentNavigation(url);
-}
-
 void Document::statePopped(PassRefPtr<SerializedScriptValue> stateObject)
 {
     if (!frame())
@@ -4768,8 +4784,11 @@
 void Document::didRemoveEventTargetNode(Node* handler)
 {
     if (m_touchEventTargets) {
-        m_touchEventTargets->removeAll(handler);
-        if ((handler == this || m_touchEventTargets->isEmpty()) && parentDocument())
+        if (handler == this)
+            m_touchEventTargets->clear();
+        else
+            m_touchEventTargets->removeAll(handler);
+        if (m_touchEventTargets->isEmpty() && parentDocument())
             parentDocument()->didRemoveEventTargetNode(this);
     }
 }
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index 4d3ba07..cd90543 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -63,8 +63,8 @@
 class CDATASection;
 class CSSStyleDeclaration;
 class CSSStyleSheet;
-class CachedCSSStyleSheet;
-class CachedScript;
+class CSSStyleSheetResource;
+class ScriptResource;
 class CanvasRenderingContext;
 class CharacterData;
 class Comment;
@@ -907,11 +907,22 @@
     void initSecurityContext(const DocumentInit&);
     void initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders&);
 
-    void updateURLForPushOrReplaceState(const KURL&);
     void statePopped(PassRefPtr<SerializedScriptValue>);
 
-    bool processingLoadEvent() const { return m_processingLoadEvent; }
-    bool loadEventFinished() const { return m_loadEventFinished; }
+    enum LoadEventProgress {
+        LoadEventNotRun,
+        LoadEventTried,
+        LoadEventInProgress,
+        LoadEventCompleted,
+        UnloadEventInProgress,
+        UnloadEventHandled
+    };
+    bool loadEventStillNeeded() const { return m_loadEventProgress == LoadEventNotRun; }
+    bool processingLoadEvent() const { return m_loadEventProgress == LoadEventInProgress; }
+    bool loadEventFinished() const { return m_loadEventProgress >= LoadEventCompleted; }
+    bool unloadEventStillNeeded() const { return m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress; }
+    void unloadEventStarted() { m_loadEventProgress = UnloadEventInProgress; }
+    void unloadEventWasHandled() { m_loadEventProgress = UnloadEventHandled; }
 
     virtual bool isContextThread() const;
     virtual bool isJSExecutionForbidden() const { return false; }
@@ -1000,7 +1011,7 @@
     void decrementActiveParserCount();
 
     void setContextFeatures(PassRefPtr<ContextFeatures>);
-    ContextFeatures* contextFeatures() { return m_contextFeatures.get(); }
+    ContextFeatures* contextFeatures() const { return m_contextFeatures.get(); }
 
     DocumentSharedObjectPool* sharedObjectPool() { return m_sharedObjectPool.get(); }
 
@@ -1030,9 +1041,18 @@
 
     virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0);
 
+    virtual DOMWindow* executingWindow() OVERRIDE { return domWindow(); }
+    virtual void userEventWasHandled() OVERRIDE { resetLastHandledUserGestureTimestamp(); }
+
     PassRefPtr<FontLoader> fontloader();
     DocumentLifecycleNotifier* lifecycleNotifier();
 
+    enum HttpRefreshType {
+        HttpRefreshFromHeader,
+        HttpRefreshFromMetaTag
+    };
+    void maybeHandleHttpRefresh(const String&, HttpRefreshType);
+
 protected:
     Document(const DocumentInit&, DocumentClassFlags = DefaultDocumentClass);
 
@@ -1042,6 +1062,8 @@
 
     virtual void dispose() OVERRIDE;
 
+    virtual PassRefPtr<Document> cloneDocumentWithoutChildren();
+
 private:
     friend class Node;
     friend class IgnoreDestructiveWriteCountIncrementer;
@@ -1061,6 +1083,7 @@
     virtual NodeType nodeType() const;
     virtual bool childTypeAllowed(NodeType) const;
     virtual PassRefPtr<Node> cloneNode(bool deep = true);
+    void cloneDataFromDocument(const Document&);
 
     virtual void refScriptExecutionContext() { ref(); }
     virtual void derefScriptExecutionContext() { deref(); }
@@ -1226,12 +1249,7 @@
 
     Element* m_cssTarget;
 
-    // FIXME: Merge these 2 variables into an enum. Also, FrameLoader::m_didCallImplicitClose
-    // is almost a duplication of this data, so that should probably get merged in too.
-    // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadHandled are roughly the same
-    // and should be merged.
-    bool m_processingLoadEvent;
-    bool m_loadEventFinished;
+    LoadEventProgress m_loadEventProgress;
 
     RefPtr<SerializedScriptValue> m_pendingStateObject;
     double m_startTime;
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index 3e1af34..0fc91ba 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -29,7 +29,7 @@
     readonly attribute DOMImplementation implementation;
     readonly attribute Element documentElement;
 
-    [DeliverCustomElementCallbacks, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElement([TreatNullAs=NullString,Default=Undefined] optional DOMString tagName);
+    [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElement([TreatNullAs=NullString,Default=Undefined] optional DOMString tagName);
     DocumentFragment   createDocumentFragment();
     [PerWorldBindings] Text createTextNode([Default=Undefined] optional DOMString data);
     Comment createComment([Default=Undefined] optional DOMString data);
@@ -41,9 +41,9 @@
 
     // Introduced in DOM Level 2:
 
-    [DeliverCustomElementCallbacks, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Node importNode([Default=Undefined] optional Node importedNode,
+    [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Node importNode([Default=Undefined] optional Node importedNode,
                     optional boolean deep);
-    [DeliverCustomElementCallbacks, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
+    [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                             [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName);
     [RaisesException] Attr createAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                                                           [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName);
@@ -59,7 +59,7 @@
              [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString xmlVersion;
              [SetterRaisesException] attribute boolean xmlStandalone;
 
-    [RaisesException] Node               adoptNode([Default=Undefined] optional Node source);
+    [RaisesException, CustomElementCallbacks=Enable] Node               adoptNode([Default=Undefined] optional Node source);
 
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString documentURI;
 
@@ -98,7 +98,7 @@
                                                         [Default=Undefined] optional DOMString pseudoElement);
 
     // Common extensions
-    [DeliverCustomElementCallbacks]
+    [CustomElementCallbacks=Enable]
     boolean            execCommand([Default=Undefined] optional DOMString command,
                                    [Default=Undefined] optional boolean userInterface,
                                    [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString value);
@@ -111,14 +111,14 @@
 
     // Moved down from HTMLDocument
 
-             [TreatNullAs=NullString] attribute DOMString title;
+             [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString title;
     readonly attribute DOMString referrer;
              [TreatNullAs=NullString, SetterRaisesException] attribute DOMString domain;
     readonly attribute DOMString URL;
 
              [TreatNullAs=NullString, GetterRaisesException, SetterRaisesException] attribute DOMString cookie;
 
-             [SetterRaisesException] attribute HTMLElement body;
+             [SetterRaisesException, CustomElementCallbacks=Enable] attribute HTMLElement body;
 
     readonly attribute HTMLHeadElement head;
     readonly attribute HTMLCollection images;
@@ -171,82 +171,82 @@
     [EnabledAtRuntime=fontLoadEvents] readonly attribute FontLoader fontloader;
 
     // Event handler DOM attributes
-    [NotEnumerable] attribute EventListener onabort;
-    [NotEnumerable] attribute EventListener onblur;
-    [NotEnumerable] attribute EventListener onchange;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onclick;
-    [NotEnumerable] attribute EventListener oncontextmenu;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondblclick;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrag;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragend;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragenter;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragleave;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragover;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragstart;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrop;
-    [NotEnumerable] attribute EventListener onerror;
-    [NotEnumerable] attribute EventListener onfocus;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener oninput;
-    [NotEnumerable] attribute EventListener oninvalid;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeydown;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeypress;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeyup;
-    [NotEnumerable] attribute EventListener onload;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousedown;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseenter;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseleave;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousemove;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseout;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseover;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseup;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousewheel;
-    [NotEnumerable] attribute EventListener onreadystatechange;
-    [NotEnumerable] attribute EventListener onscroll;
-    [NotEnumerable] attribute EventListener onselect;
-    [NotEnumerable] attribute EventListener onsubmit;
+    [NotEnumerable] attribute EventHandler onabort;
+    [NotEnumerable] attribute EventHandler onblur;
+    [NotEnumerable] attribute EventHandler onchange;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onclick;
+    [NotEnumerable] attribute EventHandler oncontextmenu;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondblclick;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrag;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragend;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragenter;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragleave;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragover;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragstart;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrop;
+    [NotEnumerable] attribute EventHandler onerror;
+    [NotEnumerable] attribute EventHandler onfocus;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler oninput;
+    [NotEnumerable] attribute EventHandler oninvalid;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeydown;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeypress;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeyup;
+    [NotEnumerable] attribute EventHandler onload;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousedown;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseenter;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseleave;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousemove;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel;
+    [NotEnumerable] attribute EventHandler onreadystatechange;
+    [NotEnumerable] attribute EventHandler onscroll;
+    [NotEnumerable] attribute EventHandler onselect;
+    [NotEnumerable] attribute EventHandler onsubmit;
 
-    // attribute [NotEnumerable] EventListener oncanplay;
-    // attribute [NotEnumerable] EventListener oncanplaythrough;
-    // attribute [NotEnumerable] EventListener ondurationchange;
-    // attribute [NotEnumerable] EventListener onemptied;
-    // attribute [NotEnumerable] EventListener onended;
-    // attribute [NotEnumerable] EventListener onloadeddata;
-    // attribute [NotEnumerable] EventListener onloadedmetadata;
-    // attribute [NotEnumerable] EventListener onloadstart;
-    // attribute [NotEnumerable] EventListener onpause;
-    // attribute [NotEnumerable] EventListener onplay;
-    // attribute [NotEnumerable] EventListener onplaying;
-    // attribute [NotEnumerable] EventListener onprogress;
-    // attribute [NotEnumerable] EventListener onratechange;
-    // attribute [NotEnumerable] EventListener onseeked;
-    // attribute [NotEnumerable] EventListener onseeking;
-    // attribute [NotEnumerable] EventListener onshow;
-    // attribute [NotEnumerable] EventListener onstalled;
-    // attribute [NotEnumerable] EventListener onsuspend;
-    // attribute [NotEnumerable] EventListener ontimeupdate;
-    // attribute [NotEnumerable] EventListener onvolumechange;
-    // attribute [NotEnumerable] EventListener onwaiting;
+    // attribute [NotEnumerable] EventHandler oncanplay;
+    // attribute [NotEnumerable] EventHandler oncanplaythrough;
+    // attribute [NotEnumerable] EventHandler ondurationchange;
+    // attribute [NotEnumerable] EventHandler onemptied;
+    // attribute [NotEnumerable] EventHandler onended;
+    // attribute [NotEnumerable] EventHandler onloadeddata;
+    // attribute [NotEnumerable] EventHandler onloadedmetadata;
+    // attribute [NotEnumerable] EventHandler onloadstart;
+    // attribute [NotEnumerable] EventHandler onpause;
+    // attribute [NotEnumerable] EventHandler onplay;
+    // attribute [NotEnumerable] EventHandler onplaying;
+    // attribute [NotEnumerable] EventHandler onprogress;
+    // attribute [NotEnumerable] EventHandler onratechange;
+    // attribute [NotEnumerable] EventHandler onseeked;
+    // attribute [NotEnumerable] EventHandler onseeking;
+    // attribute [NotEnumerable] EventHandler onshow;
+    // attribute [NotEnumerable] EventHandler onstalled;
+    // attribute [NotEnumerable] EventHandler onsuspend;
+    // attribute [NotEnumerable] EventHandler ontimeupdate;
+    // attribute [NotEnumerable] EventHandler onvolumechange;
+    // attribute [NotEnumerable] EventHandler onwaiting;
 
     // WebKit extensions
-    [NotEnumerable] attribute EventListener onbeforecut;
-    [NotEnumerable] attribute EventListener oncut;
-    [NotEnumerable] attribute EventListener onbeforecopy;
-    [NotEnumerable] attribute EventListener oncopy;
-    [NotEnumerable] attribute EventListener onbeforepaste;
-    [NotEnumerable] attribute EventListener onpaste;
-    [NotEnumerable] attribute EventListener onreset;
-    [NotEnumerable] attribute EventListener onsearch;
-    [NotEnumerable] attribute EventListener onselectstart;
-    [NotEnumerable] attribute EventListener onselectionchange;
-    [NotEnumerable,EnabledAtRuntime=touch] attribute EventListener ontouchstart;
-    [NotEnumerable,EnabledAtRuntime=touch] attribute EventListener ontouchmove;
-    [NotEnumerable,EnabledAtRuntime=touch] attribute EventListener ontouchend;
-    [NotEnumerable,EnabledAtRuntime=touch] attribute EventListener ontouchcancel;
-    [NotEnumerable] attribute EventListener onwebkitfullscreenchange;
-    [NotEnumerable] attribute EventListener onwebkitfullscreenerror;
-    [NotEnumerable] attribute EventListener onwebkitpointerlockchange;
-    [NotEnumerable] attribute EventListener onwebkitpointerlockerror;
-    [NotEnumerable, EnabledAtRuntime=experimentalContentSecurityPolicyFeatures] attribute EventListener onsecuritypolicyviolation;
+    [NotEnumerable] attribute EventHandler onbeforecut;
+    [NotEnumerable] attribute EventHandler oncut;
+    [NotEnumerable] attribute EventHandler onbeforecopy;
+    [NotEnumerable] attribute EventHandler oncopy;
+    [NotEnumerable] attribute EventHandler onbeforepaste;
+    [NotEnumerable] attribute EventHandler onpaste;
+    [NotEnumerable] attribute EventHandler onreset;
+    [NotEnumerable] attribute EventHandler onsearch;
+    [NotEnumerable] attribute EventHandler onselectstart;
+    [NotEnumerable] attribute EventHandler onselectionchange;
+    [NotEnumerable,EnabledAtRuntime=touch] attribute EventHandler ontouchstart;
+    [NotEnumerable,EnabledAtRuntime=touch] attribute EventHandler ontouchmove;
+    [NotEnumerable,EnabledAtRuntime=touch] attribute EventHandler ontouchend;
+    [NotEnumerable,EnabledAtRuntime=touch] attribute EventHandler ontouchcancel;
+    [NotEnumerable] attribute EventHandler onwebkitfullscreenchange;
+    [NotEnumerable] attribute EventHandler onwebkitfullscreenerror;
+    [NotEnumerable] attribute EventHandler onwebkitpointerlockchange;
+    [NotEnumerable] attribute EventHandler onwebkitpointerlockerror;
+    [NotEnumerable, EnabledAtRuntime=experimentalContentSecurityPolicyFeatures] attribute EventHandler onsecuritypolicyviolation;
 
     [EnabledAtRuntime=touch] Touch createTouch([Default=Undefined] optional Window window,
                                                [Default=Undefined] optional EventTarget target,
@@ -261,10 +261,10 @@
                                                [Default=Undefined] optional float webkitForce);
     [EnabledAtRuntime=touch, Custom, RaisesException] TouchList createTouchList();
 
-    [DeprecateAs=PrefixedDocumentRegister, EnabledAtRuntime=customDOMElements, ImplementedAs=registerElement, CallWith=ScriptState, DeliverCustomElementCallbacks, RaisesException] CustomElementConstructor webkitRegister(DOMString name, optional Dictionary options);
-    [EnabledAtRuntime=customDOMElements, ImplementedAs=registerElement, CallWith=ScriptState, DeliverCustomElementCallbacks, RaisesException] CustomElementConstructor register(DOMString name, optional Dictionary options);
-    [DeliverCustomElementCallbacks, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElement(DOMString localName, [TreatNullAs=NullString] DOMString typeExtension);
-    [DeliverCustomElementCallbacks, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName,
+    [DeprecateAs=PrefixedDocumentRegister, EnabledAtRuntime=customDOMElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor webkitRegister(DOMString name, optional Dictionary options);
+    [EnabledAtRuntime=customDOMElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor register(DOMString name, optional Dictionary options);
+    [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElement(DOMString localName, [TreatNullAs=NullString] DOMString typeExtension);
+    [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName,
                             [TreatNullAs=NullString] DOMString typeExtension);
 
     // Page visibility API.
diff --git a/Source/core/dom/DocumentOrderedMap.cpp b/Source/core/dom/DocumentOrderedMap.cpp
index 76f236a..ee4c389 100644
--- a/Source/core/dom/DocumentOrderedMap.cpp
+++ b/Source/core/dom/DocumentOrderedMap.cpp
@@ -37,6 +37,7 @@
 #include "core/dom/TreeScope.h"
 #include "core/html/HTMLLabelElement.h"
 #include "core/html/HTMLMapElement.h"
+#include "core/html/HTMLNameCollection.h"
 
 namespace WebCore {
 
@@ -47,6 +48,11 @@
     return element->getIdAttribute().impl() == key;
 }
 
+inline bool keyMatchesName(StringImpl* key, Element* element)
+{
+    return element->getNameAttribute().impl() == key;
+}
+
 inline bool keyMatchesMapName(StringImpl* key, Element* element)
 {
     return element->hasTagName(mapTag) && toHTMLMapElement(element)->getName().impl() == key;
@@ -65,7 +71,6 @@
 void DocumentOrderedMap::clear()
 {
     m_map.clear();
-    m_duplicateCounts.clear();
 }
 
 void DocumentOrderedMap::add(StringImpl* key, Element* element)
@@ -73,29 +78,15 @@
     ASSERT(key);
     ASSERT(element);
 
-    if (!m_duplicateCounts.contains(key)) {
-        // Fast path. The key is not already in m_duplicateCounts, so we assume that it's
-        // also not already in m_map and try to add it. If that add succeeds, we're done.
-        Map::AddResult addResult = m_map.add(key, element);
-        if (addResult.isNewEntry)
-            return;
+    Map::AddResult addResult = m_map.add(key, MapEntry(element));
+    if (addResult.isNewEntry)
+        return;
 
-        // The add failed, so this key was already cached in m_map.
-        // There are multiple elements with this key. Remove the m_map
-        // cache for this key so get searches for it next time it is called.
-        m_map.remove(addResult.iterator);
-        m_duplicateCounts.add(key);
-    } else {
-        // There are multiple elements with this key. Remove the m_map
-        // cache for this key so get will search for it next time it is called.
-        Map::iterator cachedItem = m_map.find(key);
-        if (cachedItem != m_map.end()) {
-            m_map.remove(cachedItem);
-            m_duplicateCounts.add(key);
-        }
-    }
-
-    m_duplicateCounts.add(key);
+    MapEntry& entry = addResult.iterator->value;
+    ASSERT(entry.count);
+    entry.element = 0;
+    entry.count++;
+    entry.orderedList.clear();
 }
 
 void DocumentOrderedMap::remove(StringImpl* key, Element* element)
@@ -103,12 +94,20 @@
     ASSERT(key);
     ASSERT(element);
 
-    m_map.checkConsistency();
-    Map::iterator cachedItem = m_map.find(key);
-    if (cachedItem != m_map.end() && cachedItem->value == element)
-        m_map.remove(cachedItem);
-    else
-        m_duplicateCounts.remove(key);
+    Map::iterator it = m_map.find(key);
+    ASSERT(it != m_map.end());
+    MapEntry& entry = it->value;
+
+    ASSERT(entry.count);
+    if (entry.count == 1) {
+        ASSERT(!entry.element || entry.element == element);
+        m_map.remove(it);
+    } else {
+        if (entry.element == element)
+            entry.element = 0;
+        entry.count--;
+        entry.orderedList.clear(); // FIXME: Remove the element instead if there are only few items left.
+    }
 }
 
 template<bool keyMatches(StringImpl*, Element*)>
@@ -117,24 +116,23 @@
     ASSERT(key);
     ASSERT(scope);
 
-    m_map.checkConsistency();
+    Map::iterator it = m_map.find(key);
+    if (it == m_map.end())
+        return 0;
 
-    Element* element = m_map.get(key);
-    if (element)
+    MapEntry& entry = it->value;
+    ASSERT(entry.count);
+    if (entry.element)
+        return entry.element;
+
+    // We know there's at least one node that matches; iterate to find the first one.
+    for (Element* element = ElementTraversal::firstWithin(scope->rootNode()); element; element = ElementTraversal::next(element)) {
+        if (!keyMatches(key, element))
+            continue;
+        entry.element = element;
         return element;
-
-    if (m_duplicateCounts.contains(key)) {
-        // We know there's at least one node that matches; iterate to find the first one.
-        for (element = ElementTraversal::firstWithin(scope->rootNode()); element; element = ElementTraversal::next(element)) {
-            if (!keyMatches(key, element))
-                continue;
-            m_duplicateCounts.remove(key);
-            m_map.set(key, element);
-            return element;
-        }
-        ASSERT_NOT_REACHED();
     }
-
+    ASSERT_NOT_REACHED();
     return 0;
 }
 
@@ -143,6 +141,11 @@
     return get<keyMatchesId>(key, scope);
 }
 
+Element* DocumentOrderedMap::getElementByName(StringImpl* key, const TreeScope* scope) const
+{
+    return get<keyMatchesName>(key, scope);
+}
+
 Element* DocumentOrderedMap::getElementByMapName(StringImpl* key, const TreeScope* scope) const
 {
     return get<keyMatchesMapName>(key, scope);
@@ -158,4 +161,31 @@
     return get<keyMatchesLabelForAttribute>(key, scope);
 }
 
+const Vector<Element*>* DocumentOrderedMap::getAllElementsById(StringImpl* key, const TreeScope* scope) const
+{
+    ASSERT(key);
+    ASSERT(scope);
+
+    Map::iterator it = m_map.find(key);
+    if (it == m_map.end())
+        return 0;
+
+    MapEntry& entry = it->value;
+    ASSERT(entry.count);
+    if (!entry.count)
+        return 0;
+
+    if (entry.orderedList.isEmpty()) {
+        entry.orderedList.reserveCapacity(entry.count);
+        for (Element* element = entry.element ? entry.element : ElementTraversal::firstWithin(scope->rootNode()); element; element = ElementTraversal::next(element)) {
+            if (!keyMatchesId(key, element))
+                continue;
+            entry.orderedList.append(element);
+        }
+        ASSERT(entry.orderedList.size() == entry.count);
+    }
+
+    return &entry.orderedList;
+}
+
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentOrderedMap.h b/Source/core/dom/DocumentOrderedMap.h
index b6fc8e0..a86caf0 100644
--- a/Source/core/dom/DocumentOrderedMap.h
+++ b/Source/core/dom/DocumentOrderedMap.h
@@ -33,6 +33,7 @@
 
 #include "wtf/HashCountedSet.h"
 #include "wtf/HashMap.h"
+#include "wtf/Vector.h"
 #include "wtf/text/StringImpl.h"
 
 namespace WebCore {
@@ -47,35 +48,60 @@
     void clear();
 
     bool contains(StringImpl*) const;
+    bool containsSingle(StringImpl*) const;
     bool containsMultiple(StringImpl*) const;
+
     // concrete instantiations of the get<>() method template
     Element* getElementById(StringImpl*, const TreeScope*) const;
+    Element* getElementByName(StringImpl*, const TreeScope*) const;
     Element* getElementByMapName(StringImpl*, const TreeScope*) const;
     Element* getElementByLowercasedMapName(StringImpl*, const TreeScope*) const;
     Element* getElementByLabelForAttribute(StringImpl*, const TreeScope*) const;
 
+    const Vector<Element*>* getAllElementsById(StringImpl*, const TreeScope*) const;
+
     void checkConsistency() const;
 
 private:
     template<bool keyMatches(StringImpl*, Element*)> Element* get(StringImpl*, const TreeScope*) const;
 
-    typedef HashMap<StringImpl*, Element*> Map;
+    struct MapEntry {
+        MapEntry()
+            : element(0)
+            , count(0)
+        {
+        }
+        explicit MapEntry(Element* firstElement)
+            : element(firstElement)
+            , count(1)
+        {
+        }
 
-    // We maintain the invariant that m_duplicateCounts is the count of all elements with a given key
-    // excluding the one referenced in m_map, if any. This means it one less than the total count
-    // when the first node with a given key is cached, otherwise the same as the total count.
+        Element* element;
+        unsigned count;
+        Vector<Element*> orderedList;
+    };
+
+    typedef HashMap<StringImpl*, MapEntry> Map;
+
     mutable Map m_map;
-    mutable HashCountedSet<StringImpl*> m_duplicateCounts;
 };
 
+inline bool DocumentOrderedMap::containsSingle(StringImpl* id) const
+{
+    Map::const_iterator it = m_map.find(id);
+    return it != m_map.end() && it->value.count == 1;
+}
+
 inline bool DocumentOrderedMap::contains(StringImpl* id) const
 {
-    return m_map.contains(id) || m_duplicateCounts.contains(id);
+    return m_map.contains(id);
 }
 
 inline bool DocumentOrderedMap::containsMultiple(StringImpl* id) const
 {
-    return m_duplicateCounts.contains(id);
+    Map::const_iterator it = m_map.find(id);
+    return it != m_map.end() && it->value.count > 1;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index 1c0ca09..0aedfec 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -1238,29 +1238,40 @@
     if (isUpgradedCustomElement() && inDocument())
         CustomElement::didEnterDocument(this, document());
 
-    TreeScope* scope = insertionPoint->treeScope();
-    if (scope != treeScope())
+    if (insertionPoint->treeScope() != treeScope())
         return InsertionDone;
 
+    HTMLDocument* newDocument = inDocument() && !isInShadowTree() && document()->isHTMLDocument() ? toHTMLDocument(document()) : 0;
+
     const AtomicString& idValue = getIdAttribute();
-    if (!idValue.isNull())
-        updateId(scope, nullAtom, idValue);
+    if (!idValue.isNull()) {
+        updateIdForTreeScope(treeScope(), nullAtom, idValue);
+        if (newDocument)
+            updateIdForDocument(newDocument, nullAtom, idValue);
+    }
 
     const AtomicString& nameValue = getNameAttribute();
-    if (!nameValue.isNull())
-        updateName(nullAtom, nameValue);
+    if (!nameValue.isNull()) {
+        updateNameForTreeScope(treeScope(), nullAtom, nameValue);
+        if (newDocument)
+            updateNameForDocument(newDocument, nullAtom, nameValue);
+    }
 
     if (hasTagName(labelTag)) {
-        if (scope->shouldCacheLabelsByForAttribute())
-            updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
+        if (treeScope()->shouldCacheLabelsByForAttribute())
+            updateLabel(treeScope(), nullAtom, fastGetAttribute(forAttr));
     }
 
+    if (parentElement() && parentElement()->isInCanvasSubtree())
+        setIsInCanvasSubtree(true);
+
     return InsertionDone;
 }
 
 void Element::removedFrom(ContainerNode* insertionPoint)
 {
     bool wasInDocument = insertionPoint->inDocument();
+    bool wasInShadowTree = isInShadowTree(); // Of course, we might still be in a shadow tree...
 
     if (Element* before = pseudoElement(BEFORE))
         before->removedFrom(insertionPoint);
@@ -1281,22 +1292,31 @@
     setSavedLayerScrollOffset(IntSize());
 
     if (insertionPoint->isInTreeScope() && treeScope() == document()) {
+        TreeScope* oldScope = insertionPoint->treeScope();
+        HTMLDocument* oldDocument = wasInDocument && !wasInShadowTree && oldScope->documentScope()->isHTMLDocument() ? toHTMLDocument(oldScope->documentScope()) : 0;
+
         const AtomicString& idValue = getIdAttribute();
-        if (!idValue.isNull())
-            updateId(insertionPoint->treeScope(), idValue, nullAtom);
+        if (!idValue.isNull()) {
+            updateIdForTreeScope(oldScope, idValue, nullAtom);
+            if (oldDocument)
+                updateIdForDocument(oldDocument, idValue, nullAtom);
+        }
 
         const AtomicString& nameValue = getNameAttribute();
-        if (!nameValue.isNull())
-            updateName(nameValue, nullAtom);
+        if (!nameValue.isNull()) {
+            updateNameForTreeScope(oldScope, nameValue, nullAtom);
+            if (oldDocument)
+                updateNameForDocument(oldDocument, nameValue, nullAtom);
+        }
 
         if (hasTagName(labelTag)) {
-            TreeScope* treeScope = insertionPoint->treeScope();
-            if (treeScope->shouldCacheLabelsByForAttribute())
-                updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
+            if (oldScope->shouldCacheLabelsByForAttribute())
+                updateLabel(oldScope, fastGetAttribute(forAttr), nullAtom);
         }
     }
 
     ContainerNode::removedFrom(insertionPoint);
+
     if (wasInDocument) {
         if (hasPendingResources())
             document()->accessSVGExtensions()->removeElementFromPendingResources(this);
@@ -1304,11 +1324,9 @@
         if (isUpgradedCustomElement())
             CustomElement::didLeaveDocument(this, insertionPoint->document());
     }
-}
 
-void Element::createRendererIfNeeded(const AttachContext& context)
-{
-    NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
+    if (hasRareData())
+        elementRareData()->setIsInCanvasSubtree(false);
 }
 
 void Element::attach(const AttachContext& context)
@@ -1317,10 +1335,7 @@
     StyleResolverParentPusher parentPusher(this);
     WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
 
-    createRendererIfNeeded(context);
-
-    if (parentElement() && parentElement()->isInCanvasSubtree())
-        setIsInCanvasSubtree(true);
+    NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
 
     createPseudoElementIfNeeded(BEFORE);
 
@@ -1368,11 +1383,14 @@
         data->setPseudoElement(BEFORE, 0);
         data->setPseudoElement(AFTER, 0);
         data->setPseudoElement(BACKDROP, 0);
-        data->setIsInCanvasSubtree(false);
-        data->resetComputedStyle();
+        data->clearComputedStyle();
         data->resetDynamicRestyleObservations();
         data->setIsInsideRegion(false);
 
+        // Only clear the style state if we're not going to reuse the style from recalcStyle.
+        if (!context.resolvedStyle)
+            data->resetStyleState();
+
         if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
             if (ActiveAnimations* activeAnimations = data->activeAnimations())
                 activeAnimations->cssAnimations()->cancel();
@@ -1449,17 +1467,16 @@
     bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
     bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
 
-    if (change > NoChange || needsStyleRecalc()) {
-        if (hasRareData())
-            elementRareData()->resetComputedStyle();
+    if (hasRareData() && (change > NoChange || needsStyleRecalc())) {
+        ElementRareData* data = elementRareData();
+        data->resetStyleState();
+        data->clearComputedStyle();
     }
+
     if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
         StyleChange localChange = Detach;
         RefPtr<RenderStyle> newStyle;
         if (currentStyle) {
-            // FIXME: This still recalcs style twice when changing display types, but saves
-            // us from recalcing twice when going from none -> anything else which is more
-            // common, especially during lazy attach.
             newStyle = styleForRenderer();
             localChange = Node::diff(currentStyle.get(), newStyle.get(), document());
         } else if (attached() && isActiveInsertionPoint(this)) {
@@ -1472,10 +1489,6 @@
             reattachContext.resolvedStyle = newStyle.get();
             reattach(reattachContext);
 
-            // attach recalculates the style for all children. No need to do it twice.
-            clearNeedsStyleRecalc();
-            clearChildNeedsStyleRecalc();
-
             if (hasCustomStyleCallbacks())
                 didRecalcStyle(change);
             return true;
@@ -1632,22 +1645,17 @@
     return shadowRoot;
 }
 
+Element* Element::uaShadowElementById(const AtomicString& id) const
+{
+    ShadowRoot* shadowRoot = userAgentShadowRoot();
+    return shadowRoot ? shadowRoot->getElementById(id) : 0;
+}
+
 bool Element::supportsShadowElementForUserAgentShadow() const
 {
     return true;
 }
 
-// FIXME: After replacing all internal shadowPseudoId with shadowPartId, remove this method.
-const AtomicString& Element::shadowPseudoId() const
-{
-    return pseudo();
-}
-
-const AtomicString& Element::shadowPartId() const
-{
-    return part();
-}
-
 bool Element::childTypeAllowed(NodeType type) const
 {
     switch (type) {
@@ -2030,7 +2038,7 @@
         // If a focus event handler changes the focus to a different node it
         // does not make sense to continue and update appearence.
         protect = this;
-        if (!page->focusController()->setFocusedElement(this, doc->frame(), direction))
+        if (!page->focusController().setFocusedElement(this, doc->frame(), direction))
             return;
     }
 
@@ -2073,8 +2081,8 @@
     cancelFocusAppearanceUpdate();
     if (treeScope()->adjustedFocusedElement() == this) {
         Document* doc = document();
-        if (doc->frame())
-            doc->frame()->page()->focusController()->setFocusedElement(0, doc->frame());
+        if (doc->page())
+            doc->page()->focusController().setFocusedElement(0, doc->frame());
         else
             doc->setFocusedElement(0);
     }
@@ -2182,17 +2190,12 @@
     return content.toString();
 }
 
-// FIXME: pseudo should be deprecated after all pseudo is replaced with ::part.
+// pseudo is used via shadowPseudoId.
 const AtomicString& Element::pseudo() const
 {
     return getAttribute(pseudoAttr);
 }
 
-void Element::setPseudo(const AtomicString& value)
-{
-    setAttribute(pseudoAttr, value);
-}
-
 const AtomicString& Element::part() const
 {
     return getAttribute(partAttr);
@@ -2763,19 +2766,47 @@
 }
 #endif
 
-inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
+void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
 {
-    if (!inDocument() || isInShadowTree())
+    if (!isInTreeScope())
         return;
 
     if (oldName == newName)
         return;
 
+    updateNameForTreeScope(treeScope(), oldName, newName);
+
+    if (!inDocument() || isInShadowTree())
+        return;
+
+    Document* htmlDocument = document();
+    if (!htmlDocument->isHTMLDocument())
+        return;
+
+    updateNameForDocument(toHTMLDocument(htmlDocument), oldName, newName);
+}
+
+void Element::updateNameForTreeScope(TreeScope* scope, const AtomicString& oldName, const AtomicString& newName)
+{
+    ASSERT(isInTreeScope());
+    ASSERT(oldName != newName);
+
+    if (!oldName.isEmpty())
+        scope->removeElementByName(oldName, this);
+    if (!newName.isEmpty())
+        scope->addElementByName(newName, this);
+}
+
+void Element::updateNameForDocument(HTMLDocument* document, const AtomicString& oldName, const AtomicString& newName)
+{
+    ASSERT(inDocument() && !isInShadowTree());
+    ASSERT(oldName != newName);
+
     if (shouldRegisterAsNamedItem())
         updateNamedItemRegistration(oldName, newName);
 }
 
-inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
+void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
 {
     if (!isInTreeScope())
         return;
@@ -2783,10 +2814,19 @@
     if (oldId == newId)
         return;
 
-    updateId(treeScope(), oldId, newId);
+    updateIdForTreeScope(treeScope(), oldId, newId);
+
+    if (!inDocument() || isInShadowTree())
+        return;
+
+    Document* htmlDocument = document();
+    if (!htmlDocument->isHTMLDocument())
+        return;
+
+    updateIdForDocument(toHTMLDocument(htmlDocument), oldId, newId);
 }
 
-inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
+void Element::updateIdForTreeScope(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
 {
     ASSERT(isInTreeScope());
     ASSERT(oldId != newId);
@@ -2795,6 +2835,12 @@
         scope->removeElementById(oldId, this);
     if (!newId.isEmpty())
         scope->addElementById(newId, this);
+}
+
+void Element::updateIdForDocument(HTMLDocument* document, const AtomicString& oldId, const AtomicString& newId)
+{
+    ASSERT(inDocument() && !isInShadowTree());
+    ASSERT(oldId != newId);
 
     if (shouldRegisterAsExtraNamedItem())
         updateExtraNamedItemRegistration(oldId, newId);
@@ -2885,8 +2931,7 @@
 
 void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
 {
-    if (!document()->isHTMLDocument())
-        return;
+    ASSERT(document()->isHTMLDocument());
 
     if (!oldName.isEmpty())
         toHTMLDocument(document())->removeNamedItem(oldName);
@@ -2897,8 +2942,7 @@
 
 void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
 {
-    if (!document()->isHTMLDocument())
-        return;
+    ASSERT(document()->isHTMLDocument());
 
     if (!oldId.isEmpty())
         toHTMLDocument(document())->removeExtraNamedItem(oldId);
@@ -3036,6 +3080,10 @@
         return;
     }
 
+    // We can't update window and document's named item maps since the presence of image and object elements depend on other attributes and children.
+    // Fortunately, those named item maps are only updated when this element is in the document, which should never be the case.
+    ASSERT(!inDocument());
+
     const AtomicString& oldID = getIdAttribute();
     const AtomicString& newID = other.getIdAttribute();
 
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index b73f890..f36faaa 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -49,6 +49,7 @@
 class ElementRareData;
 class ElementShadow;
 class ExceptionState;
+class HTMLDocument;
 class Image;
 class InputMethodContext;
 class IntSize;
@@ -446,9 +447,9 @@
 
     ShadowRoot* userAgentShadowRoot() const;
     ShadowRoot* ensureUserAgentShadowRoot();
+    Element* uaShadowElementById(const AtomicString& id) const;
     virtual bool supportsShadowElementForUserAgentShadow() const;
-    virtual const AtomicString& shadowPseudoId() const;
-    virtual const AtomicString& shadowPartId() const;
+    virtual const AtomicString& shadowPseudoId() const { return !part().isEmpty() ? part() : pseudo(); }
 
     RenderStyle* computedStyle(PseudoId = NOPSEUDO);
 
@@ -529,10 +530,8 @@
 
     virtual String title() const { return String(); }
 
-    // FIXME: pseudo should be deprecated after all pseudo is replaced with ::part.
     const AtomicString& pseudo() const;
-    void setPseudo(const AtomicString&);
-    const AtomicString& part() const;
+    virtual const AtomicString& part() const;
     void setPart(const AtomicString&);
 
     LayoutSize minimumSizeForResizing() const;
@@ -665,7 +664,7 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
-    virtual void removeAllEventListeners() OVERRIDE FINAL;
+    virtual void removeAllEventListeners() OVERRIDE;
 
     virtual void willRecalcStyle(StyleChange);
     virtual void didRecalcStyle(StyleChange);
@@ -723,9 +722,12 @@
     void synchronizeAttribute(const QualifiedName&) const;
     void synchronizeAttribute(const AtomicString& localName) const;
 
-    void updateId(const AtomicString& oldId, const AtomicString& newId);
-    void updateId(TreeScope*, const AtomicString& oldId, const AtomicString& newId);
     void updateName(const AtomicString& oldName, const AtomicString& newName);
+    void updateNameForTreeScope(TreeScope*, const AtomicString& oldName, const AtomicString& newName);
+    void updateNameForDocument(HTMLDocument*, const AtomicString& oldName, const AtomicString& newName);
+    void updateId(const AtomicString& oldId, const AtomicString& newId);
+    void updateIdForTreeScope(TreeScope*, const AtomicString& oldId, const AtomicString& newId);
+    void updateIdForDocument(HTMLDocument*, const AtomicString& oldId, const AtomicString& newId);
     void updateLabel(TreeScope*, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue);
 
     void scrollByUnits(int units, ScrollGranularity);
@@ -784,8 +786,6 @@
     void detachAttrNodeFromElementWithValue(Attr*, const AtomicString& value);
     void detachAttrNodeAtIndex(Attr*, size_t index);
 
-    void createRendererIfNeeded(const AttachContext&);
-
     bool isJavaScriptURLAttribute(const Attribute&) const;
 
     RefPtr<ElementData> m_elementData;
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index cc9631f..0137af9 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -27,12 +27,12 @@
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString tagName;
 
     [TreatReturnedNullStringAs=Null] DOMString getAttribute([Default=Undefined] optional DOMString name);
-    [RaisesException, DeliverCustomElementCallbacks] void setAttribute([Default=Undefined] optional DOMString name,
+    [RaisesException, CustomElementCallbacks=Enable] void setAttribute([Default=Undefined] optional DOMString name,
                                      [Default=Undefined] optional DOMString value);
-    [DeliverCustomElementCallbacks] void removeAttribute([Default=Undefined] optional DOMString name);
+    [CustomElementCallbacks=Enable] void removeAttribute([Default=Undefined] optional DOMString name);
     Attr getAttributeNode([Default=Undefined] optional DOMString name);
-    [RaisesException, DeliverCustomElementCallbacks] Attr setAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr newAttr);
-    [RaisesException, DeliverCustomElementCallbacks] Attr removeAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr oldAttr);
+    [RaisesException, CustomElementCallbacks=Enable] Attr setAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr newAttr);
+    [RaisesException, CustomElementCallbacks=Enable] Attr removeAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr oldAttr);
     [PerWorldBindings] NodeList getElementsByTagName([Default=Undefined] optional DOMString name);
 
     // For ObjC this is defined on Node for legacy support.
@@ -43,16 +43,16 @@
 
      DOMString getAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                             [Default=Undefined] optional DOMString localName);
-     [RaisesException, DeliverCustomElementCallbacks] void setAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
+     [RaisesException, CustomElementCallbacks=Enable] void setAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                        [Default=Undefined] optional DOMString qualifiedName,
                                        [Default=Undefined] optional DOMString value);
-     [DeliverCustomElementCallbacks] void removeAttributeNS([TreatNullAs=NullString] DOMString namespaceURI,
+     [CustomElementCallbacks=Enable] void removeAttributeNS([TreatNullAs=NullString] DOMString namespaceURI,
                                           DOMString localName);
      NodeList getElementsByTagNameNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                                    [Default=Undefined] optional DOMString localName);
      Attr getAttributeNodeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                            [Default=Undefined] optional DOMString localName);
-    [RaisesException] Attr setAttributeNodeNS([Default=Undefined, StrictTypeChecking] optional Attr newAttr);
+    [RaisesException, CustomElementCallbacks=Enable] Attr setAttributeNodeNS([Default=Undefined, StrictTypeChecking] optional Attr newAttr);
     boolean hasAttribute(DOMString name);
      boolean hasAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                           [Default=Undefined] optional DOMString localName);
@@ -109,6 +109,7 @@
     [EnabledAtRuntime=ShadowDOM, Reflect, PerWorldBindings] attribute DOMString pseudo;
     [EnabledAtRuntime=ShadowDOM, RaisesException] ShadowRoot createShadowRoot();
     [EnabledAtRuntime=ShadowDOM, PerWorldBindings] readonly attribute ShadowRoot shadowRoot;
+    [EnabledAtRuntime=ShadowDOM, PerWorldBindings] NodeList getDestinationInsertionPoints();
 
     // To-be-deprecated prefixed Shadow DOM API
     [Reflect=pseudo, ImplementedAs=pseudo, PerWorldBindings, MeasureAs=ShadowDOMPrefixedPseudo] attribute DOMString webkitPseudo;
@@ -133,80 +134,79 @@
     [EnabledAtRuntime=cssRegions] sequence<Range> webkitGetRegionFlowRanges();
 
     // Event handler DOM attributes
-    [NotEnumerable, PerWorldBindings] attribute EventListener onabort;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onblur;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onchange;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onclick;
-    [NotEnumerable, PerWorldBindings] attribute EventListener oncontextmenu;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondblclick;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrag;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragend;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragenter;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragleave;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragover;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragstart;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrop;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onerror;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onfocus;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener oninput;
-    [NotEnumerable, PerWorldBindings] attribute EventListener oninvalid;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeydown;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeypress;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeyup;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onload;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousedown;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseenter;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseleave;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousemove;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseout;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseover;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseup;
-    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousewheel;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onscroll;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onselect;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onsubmit;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onabort;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onblur;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onchange;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onclick;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler oncontextmenu;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondblclick;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrag;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragend;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragenter;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragleave;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragover;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragstart;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrop;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onerror;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onfocus;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler oninput;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler oninvalid;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeydown;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeypress;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeyup;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onload;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousedown;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseenter;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseleave;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousemove;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
+    [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onscroll;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onselect;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onsubmit;
 
-    // attribute [NotEnumerable] EventListener oncanplay;
-    // attribute [NotEnumerable] EventListener oncanplaythrough;
-    // attribute [NotEnumerable] EventListener ondurationchange;
-    // attribute [NotEnumerable] EventListener onemptied;
-    // attribute [NotEnumerable] EventListener onended;
-    // attribute [NotEnumerable] EventListener onloadeddata;
-    // attribute [NotEnumerable] EventListener onloadedmetadata;
-    // attribute [NotEnumerable] EventListener onloadstart;
-    // attribute [NotEnumerable] EventListener onpause;
-    // attribute [NotEnumerable] EventListener onplay;
-    // attribute [NotEnumerable] EventListener onplaying;
-    // attribute [NotEnumerable] EventListener onprogress;
-    // attribute [NotEnumerable] EventListener onratechange;
-    // attribute [NotEnumerable] EventListener onreadystatechange;
-    // attribute [NotEnumerable] EventListener onseeked;
-    // attribute [NotEnumerable] EventListener onseeking;
-    // attribute [NotEnumerable] EventListener onshow;
-    // attribute [NotEnumerable] EventListener onstalled;
-    // attribute [NotEnumerable] EventListener onsuspend;
-    // attribute [NotEnumerable] EventListener ontimeupdate;
-    // attribute [NotEnumerable] EventListener onvolumechange;
-    // attribute [NotEnumerable] EventListener onwaiting;
+    // attribute [NotEnumerable] EventHandler oncanplay;
+    // attribute [NotEnumerable] EventHandler oncanplaythrough;
+    // attribute [NotEnumerable] EventHandler ondurationchange;
+    // attribute [NotEnumerable] EventHandler onemptied;
+    // attribute [NotEnumerable] EventHandler onended;
+    // attribute [NotEnumerable] EventHandler onloadeddata;
+    // attribute [NotEnumerable] EventHandler onloadedmetadata;
+    // attribute [NotEnumerable] EventHandler onloadstart;
+    // attribute [NotEnumerable] EventHandler onpause;
+    // attribute [NotEnumerable] EventHandler onplay;
+    // attribute [NotEnumerable] EventHandler onplaying;
+    // attribute [NotEnumerable] EventHandler onprogress;
+    // attribute [NotEnumerable] EventHandler onratechange;
+    // attribute [NotEnumerable] EventHandler onreadystatechange;
+    // attribute [NotEnumerable] EventHandler onseeked;
+    // attribute [NotEnumerable] EventHandler onseeking;
+    // attribute [NotEnumerable] EventHandler onshow;
+    // attribute [NotEnumerable] EventHandler onstalled;
+    // attribute [NotEnumerable] EventHandler onsuspend;
+    // attribute [NotEnumerable] EventHandler ontimeupdate;
+    // attribute [NotEnumerable] EventHandler onvolumechange;
+    // attribute [NotEnumerable] EventHandler onwaiting;
 
     // WebKit extensions
-    [NotEnumerable, PerWorldBindings] attribute EventListener onbeforecut;
-    [NotEnumerable, PerWorldBindings] attribute EventListener oncut;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onbeforecopy;
-    [NotEnumerable, PerWorldBindings] attribute EventListener oncopy;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onbeforepaste;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onpaste;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onreset;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onsearch;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onselectstart;
-    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventListener ontouchstart;
-    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventListener ontouchmove;
-    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventListener ontouchend;
-    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventListener ontouchcancel;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onwebkitfullscreenchange;
-    [NotEnumerable, PerWorldBindings] attribute EventListener onwebkitfullscreenerror;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onbeforecut;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler oncut;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onbeforecopy;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler oncopy;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onbeforepaste;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onpaste;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onreset;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onsearch;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onselectstart;
+    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventHandler ontouchstart;
+    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventHandler ontouchmove;
+    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventHandler ontouchend;
+    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventHandler ontouchcancel;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onwebkitfullscreenchange;
+    [NotEnumerable, PerWorldBindings] attribute EventHandler onwebkitfullscreenerror;
 };
 
 Element implements ParentNode;
 Element implements ChildNode;
-
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index e14dacb..dcc8564 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -46,7 +46,7 @@
     void setPseudoElement(PseudoId, PassRefPtr<PseudoElement>);
     PseudoElement* pseudoElement(PseudoId) const;
 
-    void resetComputedStyle();
+    void resetStyleState();
     void resetDynamicRestyleObservations();
 
     short tabIndex() const { return m_tabIndex; }
@@ -109,6 +109,7 @@
 
     RenderStyle* computedStyle() const { return m_computedStyle.get(); }
     void setComputedStyle(PassRefPtr<RenderStyle> computedStyle) { m_computedStyle = computedStyle; }
+    void clearComputedStyle() { m_computedStyle = 0; }
 
     ClassList* classList() const { return m_classList.get(); }
     void setClassList(PassOwnPtr<ClassList> classList) { m_classList = classList; }
@@ -275,7 +276,7 @@
     element->setParentOrShadowHostNode(0);
 }
 
-inline void ElementRareData::resetComputedStyle()
+inline void ElementRareData::resetStyleState()
 {
     setComputedStyle(0);
     setStyleAffectedByEmpty(false);
diff --git a/Source/core/dom/EventTarget.cpp b/Source/core/dom/EventTarget.cpp
index 233fd70..db40321 100644
--- a/Source/core/dom/EventTarget.cpp
+++ b/Source/core/dom/EventTarget.cpp
@@ -68,6 +68,13 @@
     return 0;
 }
 
+inline DOMWindow* EventTarget::executingWindow()
+{
+    if (ScriptExecutionContext* context = scriptExecutionContext())
+        return context->executingWindow();
+    return 0;
+}
+
 bool EventTarget::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
 {
     EventTargetData* d = ensureEventTargetData();
@@ -203,17 +210,14 @@
     }
 
     if (!prefixedTypeName.isEmpty()) {
-        ScriptExecutionContext* context = scriptExecutionContext();
-        if (context && context->isDocument()) {
-            Document* document = toDocument(context);
-            if (document->domWindow()) {
-                if (listenerPrefixedVector)
-                    if (listenerUnprefixedVector)
-                        UseCounter::count(document->domWindow(), UseCounter::PrefixedAndUnprefixedTransitionEndEvent);
-                    else
-                        UseCounter::count(document->domWindow(), UseCounter::PrefixedTransitionEndEvent);
-                else if (listenerUnprefixedVector)
-                    UseCounter::count(document->domWindow(), UseCounter::UnprefixedTransitionEndEvent);
+        if (DOMWindow* executingWindow = this->executingWindow()) {
+            if (listenerPrefixedVector) {
+                if (listenerUnprefixedVector)
+                    UseCounter::count(executingWindow, UseCounter::PrefixedAndUnprefixedTransitionEndEvent);
+                else
+                    UseCounter::count(executingWindow, UseCounter::PrefixedTransitionEndEvent);
+            } else if (listenerUnprefixedVector) {
+                UseCounter::count(executingWindow, UseCounter::UnprefixedTransitionEndEvent);
             }
         }
     }
@@ -231,12 +235,10 @@
     // index |size|, so iterating up to (but not including) |size| naturally excludes
     // new event listeners.
 
-    ScriptExecutionContext* context = scriptExecutionContext();
-    if (context && context->isDocument() && event->type() == eventNames().beforeunloadEvent) {
-        Document* document = toDocument(context);
-        if (DOMWindow* domWindow = document->domWindow()) {
-            if (domWindow != domWindow->top())
-                UseCounter::count(domWindow, UseCounter::SubFrameBeforeUnloadFired);
+    if (event->type() == eventNames().beforeunloadEvent) {
+        if (DOMWindow* executingWindow = this->executingWindow()) {
+            if (executingWindow->top())
+                UseCounter::count(executingWindow, UseCounter::SubFrameBeforeUnloadFired);
         }
     }
 
@@ -269,11 +271,8 @@
     }
     d->firingEventIterators->removeLast();
     if (userEventWasHandled) {
-        ScriptExecutionContext* context = scriptExecutionContext();
-        if (context && context->isDocument()) {
-            Document* document = toDocument(context);
-            document->resetLastHandledUserGestureTimestamp();
-        }
+        if (ScriptExecutionContext* context = scriptExecutionContext())
+            context->userEventWasHandled();
     }
 }
 
diff --git a/Source/core/dom/EventTarget.h b/Source/core/dom/EventTarget.h
index 5e95e0f..633d2d2 100644
--- a/Source/core/dom/EventTarget.h
+++ b/Source/core/dom/EventTarget.h
@@ -136,6 +136,7 @@
         virtual void refEventTarget() = 0;
         virtual void derefEventTarget() = 0;
 
+        DOMWindow* executingWindow();
         void fireEventListeners(Event*, EventTargetData*, EventListenerVector&);
 
         bool clearAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld);
diff --git a/Source/core/dom/MessagePort.idl b/Source/core/dom/MessagePort.idl
index aa6ddb3..4324172 100644
--- a/Source/core/dom/MessagePort.idl
+++ b/Source/core/dom/MessagePort.idl
@@ -36,6 +36,6 @@
     void close();
 
     // event handler attributes
-    attribute EventListener onmessage;
+    attribute EventHandler onmessage;
 };
 
diff --git a/Source/core/dom/NamedNodeMap.idl b/Source/core/dom/NamedNodeMap.idl
index 698a035..6169b7a 100644
--- a/Source/core/dom/NamedNodeMap.idl
+++ b/Source/core/dom/NamedNodeMap.idl
@@ -25,9 +25,9 @@
     Node getNamedItem([Default=Undefined] optional DOMString name);
     [NotEnumerable, ImplementedAs=getNamedItem] getter Node ([Default=Undefined] optional DOMString name);
 
-    [RaisesException, DeliverCustomElementCallbacks] Node setNamedItem([Default=Undefined] optional Node node);
+    [RaisesException, CustomElementCallbacks=Enable] Node setNamedItem([Default=Undefined] optional Node node);
 
-    [RaisesException, DeliverCustomElementCallbacks] Node removeNamedItem([Default=Undefined] optional DOMString name);
+    [RaisesException, CustomElementCallbacks=Enable] Node removeNamedItem([Default=Undefined] optional DOMString name);
 
     getter Node item([Default=Undefined] optional unsigned long index);
 
@@ -40,9 +40,9 @@
     /*[RaisesException]*/ Node getNamedItemNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                               [Default=Undefined] optional DOMString localName);
 
-    [RaisesException, DeliverCustomElementCallbacks] Node setNamedItemNS([Default=Undefined] optional Node node);
+    [RaisesException, CustomElementCallbacks=Enable] Node setNamedItemNS([Default=Undefined] optional Node node);
 
-    [RaisesException, DeliverCustomElementCallbacks] Node removeNamedItemNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
+    [RaisesException, CustomElementCallbacks=Enable] Node removeNamedItemNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                           [Default=Undefined] optional DOMString localName);
 
 };
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 4cc7e1e..3936024 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -652,14 +652,10 @@
 
     for (const Node* node = this; node; node = node->parentNode()) {
         if ((node->isHTMLElement() || node->isDocumentNode()) && node->renderer()) {
-#if ENABLE(USERSELECT_ALL)
             // Elements with user-select: all style are considered atomic
             // therefore non editable.
-            if (node->renderer()->style()->userSelect() == SELECT_ALL && treatment == UserSelectAllIsAlwaysNonEditable)
+            if (Position::nodeIsUserSelectAll(node) && treatment == UserSelectAllIsAlwaysNonEditable)
                 return false;
-#else
-            UNUSED_PARAM(treatment);
-#endif
             switch (node->renderer()->style()->userModify()) {
             case READ_ONLY:
                 return false;
@@ -1063,7 +1059,7 @@
             if (!next->isTextNode())
                 continue;
             ASSERT(!next->renderer());
-            toText(next)->createTextRendererIfNeeded();
+            toText(next)->reattach();
             // If we again decided not to create a renderer for next, we can bail out the loop,
             // because it won't affect the result of Text::textRendererIsNeeded() for the rest
             // of sibling nodes.
@@ -2622,6 +2618,22 @@
         node->incrementConnectedSubframeCount(count);
 }
 
+PassRefPtr<NodeList> Node::getDestinationInsertionPoints()
+{
+    document()->updateDistributionForNodeIfNeeded(this);
+    Vector<InsertionPoint*, 8> insertionPoints;
+    collectInsertionPointsWhereNodeIsDistributed(this, insertionPoints);
+    for (size_t i = 0; i < insertionPoints.size(); ++i) {
+        InsertionPoint* insertionPoint = insertionPoints[i];
+        ASSERT(insertionPoint->containingShadowRoot());
+        if (insertionPoint->containingShadowRoot()->type() == ShadowRoot::UserAgentShadowRoot)
+            return StaticNodeList::createEmpty();
+    }
+    Vector<RefPtr<Node> > asNodes;
+    asNodes.appendRange(insertionPoints.begin(), insertionPoints.end());
+    return StaticNodeList::adopt(asNodes);
+}
+
 void Node::registerScopedHTMLStyleChild()
 {
     setHasScopedHTMLStyleChild(true);
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index 58df434..a651d06 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -711,6 +711,8 @@
     void updateAncestorConnectedSubframeCountForRemoval() const;
     void updateAncestorConnectedSubframeCountForInsertion() const;
 
+    PassRefPtr<NodeList> getDestinationInsertionPoints();
+
 private:
     enum NodeFlags {
         IsTextFlag = 1,
diff --git a/Source/core/dom/Node.idl b/Source/core/dom/Node.idl
index 64f5b1e..0c7c5a1 100644
--- a/Source/core/dom/Node.idl
+++ b/Source/core/dom/Node.idl
@@ -39,7 +39,7 @@
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString        nodeName;
 
              // FIXME: the spec says this can also raise on retrieval.
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings] attribute DOMString        nodeValue;
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, CustomElementCallbacks=Enable] attribute DOMString nodeValue;
 
     [PerWorldBindings] readonly attribute unsigned short   nodeType;
     [PerWorldBindings] readonly attribute Node             parentNode;
@@ -56,9 +56,9 @@
     [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Node appendChild(Node newChild);
 
     boolean            hasChildNodes();
-    [DeliverCustomElementCallbacks, PerWorldBindings]
+    [CustomElementCallbacks=Enable, PerWorldBindings]
     Node               cloneNode(optional boolean deep);
-    void               normalize();
+    [CustomElementCallbacks=Enable] void normalize();
 
     // Introduced in DOM Level 2:
      boolean isSupported([Default=Undefined] optional DOMString feature,
@@ -72,7 +72,7 @@
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString       baseURI;
 
              // FIXME: the spec says this can also raise on retrieval.
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException, DeliverCustomElementCallbacks] attribute DOMString       textContent;
+             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException, CustomElementCallbacks=Enable] attribute DOMString       textContent;
 
     boolean            isSameNode([Default=Undefined] optional Node other);
     boolean            isEqualNode([Default=Undefined] optional Node other);
diff --git a/Source/core/dom/NodeRenderingTraversal.h b/Source/core/dom/NodeRenderingTraversal.h
index 13fb985..2db8aaf 100644
--- a/Source/core/dom/NodeRenderingTraversal.h
+++ b/Source/core/dom/NodeRenderingTraversal.h
@@ -80,6 +80,13 @@
     return parent(node, &unusedDetails);
 }
 
+inline Element* parentElement(const Node* node)
+{
+    ParentDetails unusedDetails;
+    Node* found = parent(node, &unusedDetails);
+    return found && found->isElementNode() ? toElement(found) : 0;
+}
+
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/PendingScript.cpp b/Source/core/dom/PendingScript.cpp
index 582cead..aab3343 100644
--- a/Source/core/dom/PendingScript.cpp
+++ b/Source/core/dom/PendingScript.cpp
@@ -27,38 +27,38 @@
 #include "core/dom/PendingScript.h"
 
 #include "core/dom/Element.h"
-#include "core/loader/cache/CachedScript.h"
+#include "core/loader/cache/ScriptResource.h"
 
 namespace WebCore {
 
 PendingScript::~PendingScript()
 {
-    if (m_cachedScript)
-        m_cachedScript->removeClient(this);
+    if (m_resource)
+        m_resource->removeClient(this);
 }
 
 PassRefPtr<Element> PendingScript::releaseElementAndClear()
 {
-    setCachedScript(0);
+    setScriptResource(0);
     m_watchingForLoad = false;
     m_startingPosition = TextPosition::belowRangePosition();
     return m_element.release();
 }
 
-void PendingScript::setCachedScript(CachedScript* cachedScript)
+void PendingScript::setScriptResource(ScriptResource* resource)
 {
-    if (m_cachedScript == cachedScript)
+    if (m_resource == resource)
         return;
-    if (m_cachedScript)
-        m_cachedScript->removeClient(this);
-    m_cachedScript = cachedScript;
-    if (m_cachedScript)
-        m_cachedScript->addClient(this);
+    if (m_resource)
+        m_resource->removeClient(this);
+    m_resource = resource;
+    if (m_resource)
+        m_resource->addClient(this);
 }
 
-CachedScript* PendingScript::cachedScript() const
+ScriptResource* PendingScript::resource() const
 {
-    return m_cachedScript.get();
+    return m_resource.get();
 }
 
 void PendingScript::notifyFinished(Resource*)
diff --git a/Source/core/dom/PendingScript.h b/Source/core/dom/PendingScript.h
index e5be4d3..bf902b2 100644
--- a/Source/core/dom/PendingScript.h
+++ b/Source/core/dom/PendingScript.h
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-class CachedScript;
+class ScriptResource;
 class Element;
 
 // A container for an external script which may be loaded and executed.
@@ -50,11 +50,11 @@
     {
     }
 
-    PendingScript(Element* element, CachedScript* cachedScript)
+    PendingScript(Element* element, ScriptResource* resource)
         : m_watchingForLoad(false)
         , m_element(element)
     {
-        setCachedScript(cachedScript);
+        setScriptResource(resource);
     }
 
     PendingScript(const PendingScript& other)
@@ -63,7 +63,7 @@
         , m_element(other.m_element)
         , m_startingPosition(other.m_startingPosition)
     {
-        setCachedScript(other.cachedScript());
+        setScriptResource(other.resource());
     }
 
     ~PendingScript();
@@ -76,7 +76,7 @@
         m_watchingForLoad = other.m_watchingForLoad;
         m_element = other.m_element;
         m_startingPosition = other.m_startingPosition;
-        setCachedScript(other.cachedScript());
+        setScriptResource(other.resource());
 
         return *this;
     }
@@ -91,8 +91,8 @@
     void setElement(Element* element) { m_element = element; }
     PassRefPtr<Element> releaseElementAndClear();
 
-    CachedScript* cachedScript() const;
-    void setCachedScript(CachedScript*);
+    ScriptResource* resource() const;
+    void setScriptResource(ScriptResource*);
 
     virtual void notifyFinished(Resource*);
 
@@ -100,7 +100,7 @@
     bool m_watchingForLoad;
     RefPtr<Element> m_element;
     TextPosition m_startingPosition; // Only used for inline script tags.
-    ResourcePtr<CachedScript> m_cachedScript;
+    ResourcePtr<ScriptResource> m_resource;
 };
 
 }
diff --git a/Source/core/dom/Position.cpp b/Source/core/dom/Position.cpp
index c917fb5..c71c102 100644
--- a/Source/core/dom/Position.cpp
+++ b/Source/core/dom/Position.cpp
@@ -852,10 +852,9 @@
     return node->parentNode();
 }
 
-#if ENABLE(USERSELECT_ALL)
 bool Position::nodeIsUserSelectAll(const Node* node)
 {
-    return node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_ALL;
+    return RuntimeEnabledFeatures::userSelectAllEnabled() && node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_ALL;
 }
 
 Node* Position::rootUserSelectAllForNode(Node* node)
@@ -879,7 +878,6 @@
     }
     return candidateRoot;
 }
-#endif
 
 bool Position::isCandidate() const
 {
diff --git a/Source/core/dom/Position.h b/Source/core/dom/Position.h
index 7a30694..4189054 100644
--- a/Source/core/dom/Position.h
+++ b/Source/core/dom/Position.h
@@ -189,10 +189,9 @@
 
     static bool hasRenderedNonAnonymousDescendantsWithHeight(RenderObject*);
     static bool nodeIsUserSelectNone(Node*);
-#if ENABLE(USERSELECT_ALL)
     static bool nodeIsUserSelectAll(const Node*);
     static Node* rootUserSelectAllForNode(Node*);
-#endif
+
     static ContainerNode* findParent(const Node*);
 
     void debugPosition(const char* msg = "") const;
diff --git a/Source/core/dom/ProcessingInstruction.cpp b/Source/core/dom/ProcessingInstruction.cpp
index e553a07..def6f8e 100644
--- a/Source/core/dom/ProcessingInstruction.cpp
+++ b/Source/core/dom/ProcessingInstruction.cpp
@@ -27,10 +27,10 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
-#include "core/loader/cache/CachedXSLStyleSheet.h"
+#include "core/loader/cache/CSSStyleSheetResource.h"
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/ResourceFetcher.h"
+#include "core/loader/cache/XSLStyleSheetResource.h"
 #include "core/xml/XSLStyleSheet.h"
 #include "core/xml/parser/XMLDocumentParser.h" // for parseAttributes()
 
@@ -40,7 +40,7 @@
     : Node(document, CreateOther)
     , m_target(target)
     , m_data(data)
-    , m_cachedSheet(0)
+    , m_resource(0)
     , m_loading(false)
     , m_alternate(false)
     , m_createdByParser(false)
@@ -60,8 +60,8 @@
     if (m_sheet)
         m_sheet->clearOwnerNode();
 
-    if (m_cachedSheet)
-        m_cachedSheet->removeClient(this);
+    if (m_resource)
+        m_resource->removeClient(this);
 
     if (inDocument())
         document()->styleSheetCollection()->removeStyleSheetCandidateNode(this);
@@ -142,9 +142,9 @@
                 m_loading = false;
             }
         } else {
-            if (m_cachedSheet) {
-                m_cachedSheet->removeClient(this);
-                m_cachedSheet = 0;
+            if (m_resource) {
+                m_resource->removeClient(this);
+                m_resource = 0;
             }
 
             String url = document()->completeURL(href).string();
@@ -155,7 +155,7 @@
             document()->styleSheetCollection()->addPendingSheet();
             FetchRequest request(ResourceRequest(document()->completeURL(href)), FetchInitiatorTypeNames::processinginstruction);
             if (m_isXSL)
-                m_cachedSheet = document()->fetcher()->requestXSLStyleSheet(request);
+                m_resource = document()->fetcher()->requestXSLStyleSheet(request);
             else
             {
                 String charset = attrs.get("charset");
@@ -163,10 +163,10 @@
                     charset = document()->charset();
                 request.setCharset(charset);
 
-                m_cachedSheet = document()->fetcher()->requestCSSStyleSheet(request);
+                m_resource = document()->fetcher()->requestCSSStyleSheet(request);
             }
-            if (m_cachedSheet)
-                m_cachedSheet->addClient(this);
+            if (m_resource)
+                m_resource->addClient(this);
             else {
                 // The request may have been denied if (for example) the stylesheet is local and the document is remote.
                 m_loading = false;
@@ -194,7 +194,7 @@
     return false;
 }
 
-void ProcessingInstruction::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CachedCSSStyleSheet* sheet)
+void ProcessingInstruction::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* sheet)
 {
     if (!inDocument()) {
         ASSERT(!m_sheet);
@@ -233,9 +233,9 @@
     else if (m_isXSL)
         static_cast<XSLStyleSheet*>(m_sheet.get())->parseString(sheet);
 
-    if (m_cachedSheet)
-        m_cachedSheet->removeClient(this);
-    m_cachedSheet = 0;
+    if (m_resource)
+        m_resource->removeClient(this);
+    m_resource = 0;
 
     m_loading = false;
 
@@ -247,7 +247,7 @@
 
 void ProcessingInstruction::setCSSStyleSheet(PassRefPtr<CSSStyleSheet> sheet)
 {
-    ASSERT(!m_cachedSheet);
+    ASSERT(!m_resource);
     ASSERT(!m_loading);
     m_sheet = sheet;
     sheet->setTitle(m_title);
diff --git a/Source/core/dom/ProcessingInstruction.h b/Source/core/dom/ProcessingInstruction.h
index 5dd0a21..1ae7976 100644
--- a/Source/core/dom/ProcessingInstruction.h
+++ b/Source/core/dom/ProcessingInstruction.h
@@ -23,15 +23,15 @@
 #define ProcessingInstruction_h
 
 #include "core/dom/Node.h"
-#include "core/loader/cache/CachedStyleSheetClient.h"
 #include "core/loader/cache/ResourcePtr.h"
+#include "core/loader/cache/StyleSheetResourceClient.h"
 
 namespace WebCore {
 
 class StyleSheet;
 class CSSStyleSheet;
 
-class ProcessingInstruction FINAL : public Node, private CachedStyleSheetClient {
+class ProcessingInstruction FINAL : public Node, private StyleSheetResourceClient {
 public:
     static PassRefPtr<ProcessingInstruction> create(Document*, const String& target, const String& data);
     virtual ~ProcessingInstruction();
@@ -68,7 +68,7 @@
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
     void checkStyleSheet();
-    virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CachedCSSStyleSheet*);
+    virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*);
     virtual void setXSLStyleSheet(const String& href, const KURL& baseURL, const String& sheet);
 
     virtual bool sheetLoaded();
@@ -82,7 +82,7 @@
     String m_localHref;
     String m_title;
     String m_media;
-    ResourcePtr<Resource> m_cachedSheet;
+    ResourcePtr<Resource> m_resource;
     RefPtr<StyleSheet> m_sheet;
     bool m_loading;
     bool m_alternate;
diff --git a/Source/core/dom/Promise.idl b/Source/core/dom/Promise.idl
index fe9edf0..2550866 100644
--- a/Source/core/dom/Promise.idl
+++ b/Source/core/dom/Promise.idl
@@ -31,6 +31,7 @@
 callback PromiseInit = void (PromiseResolver resolver);
 callback AnyCallback = any (optional any value);
 [
+   GlobalContext=Window&WorkerGlobalScope,
    CustomConstructor(PromiseInit init),
    EnabledAtRuntime=promise
 ] interface Promise {
diff --git a/Source/core/dom/PromiseResolver.idl b/Source/core/dom/PromiseResolver.idl
index f2c80b4..b671070 100644
--- a/Source/core/dom/PromiseResolver.idl
+++ b/Source/core/dom/PromiseResolver.idl
@@ -29,6 +29,7 @@
  */
 
 [
+   GlobalContext=Window&WorkerGlobalScope,
    EnabledAtRuntime=promise
 ] interface PromiseResolver {
    [Custom] void fulfill(optional any value);
diff --git a/Source/core/dom/PseudoElement.cpp b/Source/core/dom/PseudoElement.cpp
index ebcc455..105ac7e 100644
--- a/Source/core/dom/PseudoElement.cpp
+++ b/Source/core/dom/PseudoElement.cpp
@@ -28,7 +28,6 @@
 #include "core/dom/PseudoElement.h"
 
 #include "core/dom/NodeRenderingContext.h"
-#include "core/inspector/InspectorInstrumentation.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderQuote.h"
 #include "core/rendering/style/ContentData.h"
@@ -43,8 +42,8 @@
 
 String PseudoElement::pseudoElementNameForEvents(PseudoId pseudoId)
 {
-    DEFINE_STATIC_LOCAL(const String, after, (ASCIILiteral("::after")));
-    DEFINE_STATIC_LOCAL(const String, before, (ASCIILiteral("::before")));
+    DEFINE_STATIC_LOCAL(const String, after, ("::after"));
+    DEFINE_STATIC_LOCAL(const String, before, ("::before"));
     switch (pseudoId) {
     case AFTER:
         return after;
@@ -66,7 +65,6 @@
 
 PseudoElement::~PseudoElement()
 {
-    InspectorInstrumentation::pseudoElementDestroyed(document()->page(), this);
 }
 
 PassRefPtr<RenderStyle> PseudoElement::customStyleForRenderer()
diff --git a/Source/core/dom/Range.idl b/Source/core/dom/Range.idl
index b926178..32edd56 100644
--- a/Source/core/dom/Range.idl
+++ b/Source/core/dom/Range.idl
@@ -52,11 +52,11 @@
      [RaisesException] short compareBoundaryPoints([Default=Undefined] optional CompareHow how,
                                                [Default=Undefined] optional Range sourceRange);
 
-    [RaisesException] void deleteContents();
-    [RaisesException] DocumentFragment extractContents();
-    [RaisesException] DocumentFragment cloneContents();
-    [RaisesException] void insertNode([Default=Undefined] optional Node newNode);
-    [RaisesException] void surroundContents([Default=Undefined] optional Node newParent);
+    [RaisesException, CustomElementCallbacks=Enable] void deleteContents();
+    [RaisesException, CustomElementCallbacks=Enable] DocumentFragment extractContents();
+    [RaisesException, CustomElementCallbacks=Enable] DocumentFragment cloneContents();
+    [RaisesException, CustomElementCallbacks=Enable] void insertNode([Default=Undefined] optional Node newNode);
+    [RaisesException, CustomElementCallbacks=Enable] void surroundContents([Default=Undefined] optional Node newParent);
     [RaisesException] Range cloneRange();
     [RaisesException] DOMString toString();
 
@@ -69,7 +69,7 @@
 
     // extensions
 
-    [RaisesException] DocumentFragment createContextualFragment([Default=Undefined] optional DOMString html);
+    [RaisesException, CustomElementCallbacks=Enable] DocumentFragment createContextualFragment([Default=Undefined] optional DOMString html);
 
     // WebKit extensions
 
diff --git a/Source/core/dom/ScriptExecutionContext.h b/Source/core/dom/ScriptExecutionContext.h
index 6e6c3b3..ee4a312 100644
--- a/Source/core/dom/ScriptExecutionContext.h
+++ b/Source/core/dom/ScriptExecutionContext.h
@@ -44,6 +44,7 @@
 namespace WebCore {
 
 class ContextLifecycleNotifier;
+class DOMWindow;
 class DatabaseContext;
 class EventListener;
 class EventQueue;
@@ -63,6 +64,9 @@
 
     virtual bool isJSExecutionForbidden() const = 0;
 
+    virtual DOMWindow* executingWindow() { return 0; }
+    virtual void userEventWasHandled() { }
+
     const KURL& url() const { return virtualURL(); }
     KURL completeURL(const String& url) const { return virtualCompleteURL(url); }
 
diff --git a/Source/core/dom/ScriptLoader.cpp b/Source/core/dom/ScriptLoader.cpp
index 4cf45bb..6d1c06b 100644
--- a/Source/core/dom/ScriptLoader.cpp
+++ b/Source/core/dom/ScriptLoader.cpp
@@ -38,9 +38,9 @@
 #include "core/html/HTMLImport.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedScript.h"
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/ResourceFetcher.h"
+#include "core/loader/cache/ScriptResource.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/Frame.h"
 #include "core/platform/MIMETypeRegistry.h"
@@ -55,7 +55,7 @@
 
 ScriptLoader::ScriptLoader(Element* element, bool parserInserted, bool alreadyStarted)
     : m_element(element)
-    , m_cachedScript(0)
+    , m_resource(0)
     , m_startLineNumber(WTF::OrdinalNumber::beforeFirst())
     , m_parserInserted(parserInserted)
     , m_isExternalScript(false)
@@ -246,11 +246,11 @@
         m_readyToBeParserExecuted = true;
     } else if (client->hasSourceAttribute() && !client->asyncAttributeValue() && !m_forceAsync) {
         m_willExecuteInOrder = true;
-        executingDocument->scriptRunner()->queueScriptForExecution(this, m_cachedScript, ScriptRunner::IN_ORDER_EXECUTION);
-        m_cachedScript->addClient(this);
+        executingDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::IN_ORDER_EXECUTION);
+        m_resource->addClient(this);
     } else if (client->hasSourceAttribute()) {
-        executingDocument->scriptRunner()->queueScriptForExecution(this, m_cachedScript, ScriptRunner::ASYNC_EXECUTION);
-        m_cachedScript->addClient(this);
+        executingDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::ASYNC_EXECUTION);
+        m_resource->addClient(this);
     } else {
         // Reset line numbering for nested writes.
         TextPosition position = elementDocument->isInDocumentWrite() ? TextPosition() : scriptStartPosition;
@@ -271,7 +271,7 @@
     if (!m_element->inDocument() || m_element->document() != elementDocument)
         return false;
 
-    ASSERT(!m_cachedScript);
+    ASSERT(!m_resource);
     if (!stripLeadingAndTrailingHTMLSpaces(sourceUrl).isEmpty()) {
         FetchRequest request(ResourceRequest(elementDocument->completeURL(sourceUrl)), m_element->localName());
 
@@ -286,11 +286,11 @@
         if (isValidScriptNonce)
             request.setContentSecurityCheck(DoNotCheckContentSecurityPolicy);
 
-        m_cachedScript = elementDocument->fetcher()->requestScript(request);
+        m_resource = elementDocument->fetcher()->requestScript(request);
         m_isExternalScript = true;
     }
 
-    if (m_cachedScript) {
+    if (m_resource) {
         return true;
     }
 
@@ -324,8 +324,8 @@
     if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber)))
         return;
 
-    if (m_isExternalScript && m_cachedScript && !m_cachedScript->mimeTypeAllowedByNosniff()) {
-        executingDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_cachedScript->url().elidedString() + "' because its MIME type ('" + m_cachedScript->mimeType() + "') is not executable, and strict MIME type checking is enabled.");
+    if (m_isExternalScript && m_resource && !m_resource->mimeTypeAllowedByNosniff()) {
+        executingDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_resource->url().elidedString() + "' because its MIME type ('" + m_resource->mimeType() + "') is not executable, and strict MIME type checking is enabled.");
         return;
     }
 
@@ -336,7 +336,7 @@
             executingDocument->pushCurrentScript(toHTMLScriptElement(m_element));
 
         AccessControlStatus corsCheck = NotSharableCrossOrigin;
-        if (sourceCode.cachedScript() && sourceCode.cachedScript()->passesAccessControlCheck(m_element->document()->securityOrigin()))
+        if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document()->securityOrigin()))
             corsCheck = SharableCrossOrigin;
 
         // Create a script from the script element node, using the script
@@ -353,24 +353,24 @@
 
 void ScriptLoader::stopLoadRequest()
 {
-    if (m_cachedScript) {
+    if (m_resource) {
         if (!m_willBeParserExecuted)
-            m_cachedScript->removeClient(this);
-        m_cachedScript = 0;
+            m_resource->removeClient(this);
+        m_resource = 0;
     }
 }
 
-void ScriptLoader::execute(CachedScript* cachedScript)
+void ScriptLoader::execute(ScriptResource* resource)
 {
     ASSERT(!m_willBeParserExecuted);
-    ASSERT(cachedScript);
-    if (cachedScript->errorOccurred()) {
+    ASSERT(resource);
+    if (resource->errorOccurred()) {
         dispatchErrorEvent();
-    } else if (!cachedScript->wasCanceled()) {
-        executeScript(ScriptSourceCode(cachedScript));
+    } else if (!resource->wasCanceled()) {
+        executeScript(ScriptSourceCode(resource));
         dispatchLoadEvent();
     }
-    cachedScript->removeClient(this);
+    resource->removeClient(this);
 }
 
 void ScriptLoader::notifyFinished(Resource* resource)
@@ -383,11 +383,11 @@
     // Resource possibly invokes this notifyFinished() more than
     // once because ScriptLoader doesn't unsubscribe itself from
     // Resource here and does it in execute() instead.
-    // We use m_cachedScript to check if this function is already called.
-    ASSERT_UNUSED(resource, resource == m_cachedScript);
-    if (!m_cachedScript)
+    // We use m_resource to check if this function is already called.
+    ASSERT_UNUSED(resource, resource == m_resource);
+    if (!m_resource)
         return;
-    if (!elementDocument->fetcher()->canAccess(m_cachedScript.get())) {
+    if (!elementDocument->fetcher()->canAccess(m_resource.get())) {
         dispatchErrorEvent();
         return;
     }
@@ -397,7 +397,7 @@
     else
         executingDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::ASYNC_EXECUTION);
 
-    m_cachedScript = 0;
+    m_resource = 0;
 }
 
 bool ScriptLoader::ignoresLoadRequest() const
diff --git a/Source/core/dom/ScriptLoader.h b/Source/core/dom/ScriptLoader.h
index c9139c1..390d83a 100644
--- a/Source/core/dom/ScriptLoader.h
+++ b/Source/core/dom/ScriptLoader.h
@@ -28,7 +28,7 @@
 
 namespace WebCore {
 
-class CachedScript;
+class ScriptResource;
 class ContainerNode;
 class Element;
 class ScriptLoaderClient;
@@ -48,7 +48,7 @@
     String scriptCharset() const { return m_characterEncoding; }
     String scriptContent() const;
     void executeScript(const ScriptSourceCode&);
-    void execute(CachedScript*);
+    void execute(ScriptResource*);
 
     // XML parser calls these
     void dispatchLoadEvent();
@@ -59,7 +59,7 @@
     bool willBeParserExecuted() const { return m_willBeParserExecuted; }
     bool readyToBeParserExecuted() const { return m_readyToBeParserExecuted; }
     bool willExecuteWhenDocumentFinishedParsing() const { return m_willExecuteWhenDocumentFinishedParsing; }
-    ResourcePtr<CachedScript> cachedScript() { return m_cachedScript; }
+    ResourcePtr<ScriptResource> resource() { return m_resource; }
 
     void setHaveFiredLoadEvent(bool haveFiredLoad) { m_haveFiredLoad = haveFiredLoad; }
     bool isParserInserted() const { return m_parserInserted; }
@@ -88,7 +88,7 @@
     virtual void notifyFinished(Resource*) OVERRIDE;
 
     Element* m_element;
-    ResourcePtr<CachedScript> m_cachedScript;
+    ResourcePtr<ScriptResource> m_resource;
     WTF::OrdinalNumber m_startLineNumber;
     bool m_parserInserted : 1;
     bool m_isExternalScript : 1;
diff --git a/Source/core/dom/ScriptRunner.cpp b/Source/core/dom/ScriptRunner.cpp
index 6289ea4..d25001e 100644
--- a/Source/core/dom/ScriptRunner.cpp
+++ b/Source/core/dom/ScriptRunner.cpp
@@ -30,7 +30,7 @@
 #include "core/dom/Element.h"
 #include "core/dom/PendingScript.h"
 #include "core/dom/ScriptLoader.h"
-#include "core/loader/cache/CachedScript.h"
+#include "core/loader/cache/ScriptResource.h"
 
 namespace WebCore {
 
@@ -51,10 +51,10 @@
         m_document->decrementLoadEventDelayCount();
 }
 
-void ScriptRunner::queueScriptForExecution(ScriptLoader* scriptLoader, ResourcePtr<CachedScript> cachedScript, ExecutionType executionType)
+void ScriptRunner::queueScriptForExecution(ScriptLoader* scriptLoader, ResourcePtr<ScriptResource> resource, ExecutionType executionType)
 {
     ASSERT(scriptLoader);
-    ASSERT(cachedScript.get());
+    ASSERT(resource.get());
 
     Element* element = scriptLoader->element();
     ASSERT(element);
@@ -64,11 +64,11 @@
 
     switch (executionType) {
     case ASYNC_EXECUTION:
-        m_pendingAsyncScripts.add(scriptLoader, PendingScript(element, cachedScript.get()));
+        m_pendingAsyncScripts.add(scriptLoader, PendingScript(element, resource.get()));
         break;
 
     case IN_ORDER_EXECUTION:
-        m_scriptsToExecuteInOrder.append(PendingScript(element, cachedScript.get()));
+        m_scriptsToExecuteInOrder.append(PendingScript(element, resource.get()));
         break;
     }
 }
@@ -109,16 +109,16 @@
     scripts.swap(m_scriptsToExecuteSoon);
 
     size_t numInOrderScriptsToExecute = 0;
-    for (; numInOrderScriptsToExecute < m_scriptsToExecuteInOrder.size() && m_scriptsToExecuteInOrder[numInOrderScriptsToExecute].cachedScript()->isLoaded(); ++numInOrderScriptsToExecute)
+    for (; numInOrderScriptsToExecute < m_scriptsToExecuteInOrder.size() && m_scriptsToExecuteInOrder[numInOrderScriptsToExecute].resource()->isLoaded(); ++numInOrderScriptsToExecute)
         scripts.append(m_scriptsToExecuteInOrder[numInOrderScriptsToExecute]);
     if (numInOrderScriptsToExecute)
         m_scriptsToExecuteInOrder.remove(0, numInOrderScriptsToExecute);
 
     size_t size = scripts.size();
     for (size_t i = 0; i < size; ++i) {
-        CachedScript* cachedScript = scripts[i].cachedScript();
+        ScriptResource* resource = scripts[i].resource();
         RefPtr<Element> element = scripts[i].releaseElementAndClear();
-        toScriptLoaderIfPossible(element.get())->execute(cachedScript);
+        toScriptLoaderIfPossible(element.get())->execute(resource);
         m_document->decrementLoadEventDelayCount();
     }
 }
diff --git a/Source/core/dom/ScriptRunner.h b/Source/core/dom/ScriptRunner.h
index e48e7e2..ef9e270 100644
--- a/Source/core/dom/ScriptRunner.h
+++ b/Source/core/dom/ScriptRunner.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class CachedScript;
+class ScriptResource;
 class Document;
 class PendingScript;
 class ScriptLoader;
@@ -47,7 +47,7 @@
     ~ScriptRunner();
 
     enum ExecutionType { ASYNC_EXECUTION, IN_ORDER_EXECUTION };
-    void queueScriptForExecution(ScriptLoader*, ResourcePtr<CachedScript>, ExecutionType);
+    void queueScriptForExecution(ScriptLoader*, ResourcePtr<ScriptResource>, ExecutionType);
     bool hasPendingScripts() const { return !m_scriptsToExecuteSoon.isEmpty() || !m_scriptsToExecuteInOrder.isEmpty() || !m_pendingAsyncScripts.isEmpty(); }
     void suspend();
     void resume();
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index 931704d..6a7878e 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -250,11 +250,6 @@
     return parentOrShadowHostNode->isSVGElement() && !parentOrShadowHostNode->hasTagName(SVGNames::foreignObjectTag);
 }
 
-void Text::createTextRendererIfNeeded()
-{
-    NodeRenderingContext(this).createRendererForTextIfNeeded();
-}
-
 RenderText* Text::createTextRenderer(RenderStyle* style)
 {
     if (isSVGText(this) || isSVGShadowText(this))
@@ -268,7 +263,7 @@
 
 void Text::attach(const AttachContext& context)
 {
-    createTextRendererIfNeeded();
+    NodeRenderingContext(this, context.resolvedStyle).createRendererForTextIfNeeded();
     CharacterData::attach(context);
 }
 
diff --git a/Source/core/dom/Text.h b/Source/core/dom/Text.h
index 2384fbd..1001eff 100644
--- a/Source/core/dom/Text.h
+++ b/Source/core/dom/Text.h
@@ -47,7 +47,6 @@
     PassRefPtr<Text> replaceWholeText(const String&);
 
     bool recalcTextStyle(StyleChange);
-    void createTextRendererIfNeeded();
     bool textRendererIsNeeded(const NodeRenderingContext&);
     virtual RenderText* createTextRenderer(RenderStyle*);
     void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData);
diff --git a/Source/core/dom/Text.idl b/Source/core/dom/Text.idl
index 0fc2704..af7360a 100644
--- a/Source/core/dom/Text.idl
+++ b/Source/core/dom/Text.idl
@@ -28,4 +28,7 @@
     // Introduced in DOM Level 3:
     readonly attribute DOMString       wholeText;
     [MeasureAs=TextReplaceWholeText] Text replaceWholeText(DOMString content); // Removed from DOM4.
+
+    // Shadow DOM API
+    [EnabledAtRuntime=ShadowDOM, PerWorldBindings] NodeList getDestinationInsertionPoints();
 };
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index 1824cc1..5ea139e 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -55,7 +55,7 @@
 
 struct SameSizeAsTreeScope {
     virtual ~SameSizeAsTreeScope();
-    void* pointers[8];
+    void* pointers[9];
     int ints[1];
 };
 
@@ -151,6 +151,15 @@
     return m_elementsById->getElementById(elementId.impl(), this);
 }
 
+const Vector<Element*>* TreeScope::getAllElementsById(const AtomicString& elementId) const
+{
+    if (elementId.isEmpty())
+        return 0;
+    if (!m_elementsById)
+        return 0;
+    return m_elementsById->getAllElementsById(elementId.impl(), this);
+}
+
 void TreeScope::addElementById(const AtomicString& elementId, Element* element)
 {
     if (!m_elementsById)
@@ -167,6 +176,29 @@
     m_idTargetObserverRegistry->notifyObservers(elementId);
 }
 
+Element* TreeScope::getElementByName(const AtomicString& name) const
+{
+    if (name.isEmpty())
+        return 0;
+    if (!m_elementsByName)
+        return 0;
+    return m_elementsByName->getElementByName(name.impl(), this);
+}
+
+void TreeScope::addElementByName(const AtomicString& name, Element* element)
+{
+    if (!m_elementsByName)
+        m_elementsByName = adoptPtr(new DocumentOrderedMap);
+    m_elementsByName->add(name.impl(), element);
+}
+
+void TreeScope::removeElementByName(const AtomicString& name, Element* element)
+{
+    if (!m_elementsByName)
+        return;
+    m_elementsByName->remove(name.impl(), element);
+}
+
 Node* TreeScope::ancestorInThisScope(Node* node) const
 {
     while (node) {
@@ -325,12 +357,7 @@
 
 bool TreeScope::applyAuthorStyles() const
 {
-    return true;
-}
-
-bool TreeScope::resetStyleInheritance() const
-{
-    return false;
+    return !rootNode()->isShadowRoot() || toShadowRoot(rootNode())->applyAuthorStyles();
 }
 
 void TreeScope::adoptIfNeeded(Node* node)
@@ -358,7 +385,7 @@
     Document* document = rootNode()->document();
     Element* element = document->focusedElement();
     if (!element && document->page())
-        element = focusedFrameOwnerElement(document->page()->focusController()->focusedFrame(), document->frame());
+        element = focusedFrameOwnerElement(document->page()->focusController().focusedFrame(), document->frame());
     if (!element)
         return 0;
     Vector<Node*> targetStack;
diff --git a/Source/core/dom/TreeScope.h b/Source/core/dom/TreeScope.h
index fa7428a..03f2607 100644
--- a/Source/core/dom/TreeScope.h
+++ b/Source/core/dom/TreeScope.h
@@ -56,10 +56,17 @@
 
     Element* adjustedFocusedElement();
     Element* getElementById(const AtomicString&) const;
-    bool hasElementWithId(StringImpl* id) const;
-    bool containsMultipleElementsWithId(const AtomicString& id) const;
-    void addElementById(const AtomicString& elementId, Element*);
-    void removeElementById(const AtomicString& elementId, Element*);
+    const Vector<Element*>* getAllElementsById(const AtomicString&) const;
+    bool hasElementWithId(StringImpl*) const; // FIXME: The argument should have type "const AtomicString&"" rather than "StringImpl*".
+    bool containsMultipleElementsWithId(const AtomicString&) const;
+    void addElementById(const AtomicString&, Element*);
+    void removeElementById(const AtomicString&, Element*);
+
+    Element* getElementByName(const AtomicString&) const;
+    bool hasElementWithName(const AtomicString&) const;
+    bool containsMultipleElementsWithName(const AtomicString&) const;
+    void addElementByName(const AtomicString&, Element*);
+    void removeElementByName(const AtomicString&, Element*);
 
     Document* documentScope() const { return m_documentScope; }
 
@@ -86,8 +93,7 @@
     // quirks mode for historical compatibility reasons.
     Element* findAnchor(const String& name);
 
-    virtual bool applyAuthorStyles() const;
-    virtual bool resetStyleInheritance() const;
+    bool applyAuthorStyles() const;
 
     // Used by the basic DOM mutation methods (e.g., appendChild()).
     void adoptIfNeeded(Node*);
@@ -168,6 +174,7 @@
     int m_guardRefCount;
 
     OwnPtr<DocumentOrderedMap> m_elementsById;
+    OwnPtr<DocumentOrderedMap> m_elementsByName;
     OwnPtr<DocumentOrderedMap> m_imageMapsByName;
     OwnPtr<DocumentOrderedMap> m_labelsByForAttribute;
 
@@ -187,6 +194,18 @@
     return m_elementsById && m_elementsById->containsMultiple(id.impl());
 }
 
+inline bool TreeScope::hasElementWithName(const AtomicString& id) const
+{
+    ASSERT(id.impl());
+    return m_elementsByName && m_elementsByName->contains(id.impl());
+}
+
+inline bool TreeScope::containsMultipleElementsWithName(const AtomicString& name) const
+{
+    ASSERT(name.impl());
+    return m_elementsByName && m_elementsByName->containsMultiple(name.impl());
+}
+
 Node* nodeFromPoint(Document*, int x, int y, LayoutPoint* localPoint = 0);
 TreeScope* commonTreeScope(Node*, Node*);
 
diff --git a/Source/core/dom/UserGestureIndicator.cpp b/Source/core/dom/UserGestureIndicator.cpp
index dc98aed..68e3feb 100644
--- a/Source/core/dom/UserGestureIndicator.cpp
+++ b/Source/core/dom/UserGestureIndicator.cpp
@@ -44,7 +44,8 @@
     virtual ~GestureToken() { }
     virtual bool hasGestures() const OVERRIDE
     {
-        if (m_consumableGestures < 1 || WTF::currentTime() - m_timestamp > (m_outOfProcess ? userGestureOutOfProcessTimeout : userGestureTimeout))
+        // Do not enforce timeouts for gestures which spawned javascript prompts.
+        if (m_consumableGestures < 1 || (WTF::currentTime() - m_timestamp > (m_outOfProcess ? userGestureOutOfProcessTimeout : userGestureTimeout) && !m_javascriptPrompt))
             return false;
         return true;
     }
@@ -55,6 +56,11 @@
         m_timestamp = WTF::currentTime();
     }
 
+    void resetTimestamp()
+    {
+        m_timestamp = WTF::currentTime();
+    }
+
     bool consumeGesture()
     {
         if (!m_consumableGestures)
@@ -71,17 +77,27 @@
             m_outOfProcess = true;
     }
 
+    virtual void setJavascriptPrompt() OVERRIDE
+    {
+        if (WTF::currentTime() - m_timestamp > userGestureTimeout)
+            return;
+        if (hasGestures())
+            m_javascriptPrompt = true;
+    }
+
 private:
     GestureToken()
         : m_consumableGestures(0),
         m_timestamp(0),
-        m_outOfProcess(false)
+        m_outOfProcess(false),
+        m_javascriptPrompt(false)
     {
     }
 
     size_t m_consumableGestures;
     double m_timestamp;
     bool m_outOfProcess;
+    bool m_javascriptPrompt;
 };
 
 }
@@ -117,16 +133,19 @@
 UserGestureIndicator::UserGestureIndicator(PassRefPtr<UserGestureToken> token)
     : m_previousState(s_state)
 {
-    if (token && static_cast<GestureToken*>(token.get())->hasGestures()) {
-        if (!s_topmostIndicator) {
-            s_topmostIndicator = this;
-            m_token = token;
-        } else {
-            m_token = s_topmostIndicator->currentToken();
-            static_cast<GestureToken*>(m_token.get())->addGesture();
-            static_cast<GestureToken*>(token.get())->consumeGesture();
+    if (token) {
+        static_cast<GestureToken*>(token.get())->resetTimestamp();
+        if (static_cast<GestureToken*>(token.get())->hasGestures()) {
+            if (!s_topmostIndicator) {
+                s_topmostIndicator = this;
+                m_token = token;
+            } else {
+                m_token = s_topmostIndicator->currentToken();
+                static_cast<GestureToken*>(m_token.get())->addGesture();
+                static_cast<GestureToken*>(token.get())->consumeGesture();
+            }
+            s_state = DefinitelyProcessingUserGesture;
         }
-        s_state = DefinitelyProcessingUserGesture;
     }
 
     ASSERT(isDefinite(s_state));
diff --git a/Source/core/dom/UserGestureIndicator.h b/Source/core/dom/UserGestureIndicator.h
index 7eaaf05..fd251f2 100644
--- a/Source/core/dom/UserGestureIndicator.h
+++ b/Source/core/dom/UserGestureIndicator.h
@@ -46,6 +46,7 @@
     virtual ~UserGestureToken() { }
     virtual bool hasGestures() const = 0;
     virtual void setOutOfProcess() = 0;
+    virtual void setJavascriptPrompt() = 0;
 };
 
 class UserGestureIndicatorDisabler {
diff --git a/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp b/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp
index 84b2fd2..c5a64fa 100644
--- a/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp
+++ b/Source/core/dom/shadow/ComposedShadowTreeWalker.cpp
@@ -58,39 +58,6 @@
     return false;
 }
 
-ComposedShadowTreeWalker ComposedShadowTreeWalker::fromFirstChild(const Node* node, Policy policy)
-{
-    ComposedShadowTreeWalker walker(node, policy);
-    walker.firstChild();
-    return walker;
-}
-
-void ComposedShadowTreeWalker::firstChild()
-{
-    assertPrecondition();
-    m_node = traverseChild(m_node, TraversalDirectionForward);
-    assertPostcondition();
-}
-
-Node* ComposedShadowTreeWalker::traverseFirstChild(const Node* node) const
-{
-    ASSERT(node);
-    return traverseChild(node, TraversalDirectionForward);
-}
-
-void ComposedShadowTreeWalker::lastChild()
-{
-    assertPrecondition();
-    m_node = traverseLastChild(m_node);
-    assertPostcondition();
-}
-
-Node* ComposedShadowTreeWalker::traverseLastChild(const Node* node) const
-{
-    ASSERT(node);
-    return traverseChild(node, TraversalDirectionBackward);
-}
-
 Node* ComposedShadowTreeWalker::traverseChild(const Node* node, TraversalDirection direction) const
 {
     ASSERT(node);
@@ -130,20 +97,6 @@
     return traverseLightChildren(node, direction);
 }
 
-void ComposedShadowTreeWalker::nextSibling()
-{
-    assertPrecondition();
-    m_node = traverseSiblingOrBackToInsertionPoint(m_node, TraversalDirectionForward);
-    assertPostcondition();
-}
-
-void ComposedShadowTreeWalker::previousSibling()
-{
-    assertPrecondition();
-    m_node = traverseSiblingOrBackToInsertionPoint(m_node, TraversalDirectionBackward);
-    assertPostcondition();
-}
-
 Node* ComposedShadowTreeWalker::traverseDistributedNodes(const Node* node, const InsertionPoint* insertionPoint, TraversalDirection direction)
 {
     for (const Node* next = node; next; next = (direction == TraversalDirectionForward ? insertionPoint->nextTo(next) : insertionPoint->previousTo(next))) {
@@ -211,13 +164,6 @@
         insertionPoint->isActive() ? traverseParent(node, details) : const_cast<Node*>(node);
 }
 
-void ComposedShadowTreeWalker::parent()
-{
-    assertPrecondition();
-    m_node = traverseParent(m_node);
-    assertPostcondition();
-}
-
 // FIXME: Use an iterative algorithm so that it can be inlined.
 // https://bugs.webkit.org/show_bug.cgi?id=90415
 Node* ComposedShadowTreeWalker::traverseParent(const Node* node, ParentTraversalDetails* details) const
@@ -269,44 +215,4 @@
     return 0;
 }
 
-Node* ComposedShadowTreeWalker::traverseNextSibling(const Node* node)
-{
-    ASSERT(node);
-    return traverseSiblingOrBackToInsertionPoint(node, TraversalDirectionForward);
-}
-
-Node* ComposedShadowTreeWalker::traversePreviousSibling(const Node* node)
-{
-    ASSERT(node);
-    return traverseSiblingOrBackToInsertionPoint(node, TraversalDirectionBackward);
-}
-
-void ComposedShadowTreeWalker::next()
-{
-    assertPrecondition();
-    if (Node* next = traverseFirstChild(m_node))
-        m_node = next;
-    else if (Node* next = traverseNextSibling(m_node))
-        m_node = next;
-    else {
-        const Node* n = m_node;
-        while (n && !traverseNextSibling(n))
-            n = traverseParent(n);
-        m_node = n ? traverseNextSibling(n) : 0;
-    }
-    assertPostcondition();
-}
-
-void ComposedShadowTreeWalker::previous()
-{
-    assertPrecondition();
-    if (Node* n = traversePreviousSibling(m_node)) {
-        while (Node* child = traverseLastChild(n))
-            n = child;
-        m_node = n;
-    } else
-        parent();
-    assertPostcondition();
-}
-
 } // namespace
diff --git a/Source/core/dom/shadow/ComposedShadowTreeWalker.h b/Source/core/dom/shadow/ComposedShadowTreeWalker.h
index d93d378..34c5b01 100644
--- a/Source/core/dom/shadow/ComposedShadowTreeWalker.h
+++ b/Source/core/dom/shadow/ComposedShadowTreeWalker.h
@@ -54,10 +54,6 @@
 
     ComposedShadowTreeWalker(const Node*, Policy = CrossUpperBoundary, StartPolicy = CannotStartFromShadowBoundary);
 
-    // For a common use case such as:
-    // for (ComposedShadowTreeWalker walker = ComposedShadowTreeWalker::fromFirstChild(node); walker.get(); walker.nextSibling())
-    static ComposedShadowTreeWalker fromFirstChild(const Node*, Policy = CrossUpperBoundary);
-
     Node* get() const { return const_cast<Node*>(m_node); }
 
     void firstChild();
@@ -141,6 +137,95 @@
 #endif
 }
 
+inline void ComposedShadowTreeWalker::parent()
+{
+    assertPrecondition();
+    m_node = traverseParent(m_node);
+    assertPostcondition();
+}
+
+inline void ComposedShadowTreeWalker::nextSibling()
+{
+    assertPrecondition();
+    m_node = traverseSiblingOrBackToInsertionPoint(m_node, TraversalDirectionForward);
+    assertPostcondition();
+}
+
+inline void ComposedShadowTreeWalker::previousSibling()
+{
+    assertPrecondition();
+    m_node = traverseSiblingOrBackToInsertionPoint(m_node, TraversalDirectionBackward);
+    assertPostcondition();
+}
+
+inline void ComposedShadowTreeWalker::next()
+{
+    assertPrecondition();
+    if (Node* next = traverseFirstChild(m_node)) {
+        m_node = next;
+    } else {
+        while (m_node) {
+            if (Node* sibling = traverseNextSibling(m_node)) {
+                m_node = sibling;
+                break;
+            }
+            m_node = traverseParent(m_node);
+        }
+    }
+    assertPostcondition();
+}
+
+inline void ComposedShadowTreeWalker::previous()
+{
+    assertPrecondition();
+    if (Node* previous = traversePreviousSibling(m_node)) {
+        while (Node* child = traverseLastChild(previous))
+            previous = child;
+        m_node = previous;
+    } else {
+        parent();
+    }
+    assertPostcondition();
+}
+
+inline void ComposedShadowTreeWalker::firstChild()
+{
+    assertPrecondition();
+    m_node = traverseChild(m_node, TraversalDirectionForward);
+    assertPostcondition();
+}
+
+inline void ComposedShadowTreeWalker::lastChild()
+{
+    assertPrecondition();
+    m_node = traverseLastChild(m_node);
+    assertPostcondition();
+}
+
+inline Node* ComposedShadowTreeWalker::traverseNextSibling(const Node* node)
+{
+    ASSERT(node);
+    return traverseSiblingOrBackToInsertionPoint(node, TraversalDirectionForward);
+}
+
+inline Node* ComposedShadowTreeWalker::traversePreviousSibling(const Node* node)
+{
+    ASSERT(node);
+    return traverseSiblingOrBackToInsertionPoint(node, TraversalDirectionBackward);
+}
+
+inline Node* ComposedShadowTreeWalker::traverseFirstChild(const Node* node) const
+{
+    ASSERT(node);
+    return traverseChild(node, TraversalDirectionForward);
+}
+
+inline Node* ComposedShadowTreeWalker::traverseLastChild(const Node* node) const
+{
+    ASSERT(node);
+    return traverseChild(node, TraversalDirectionBackward);
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 68fca88..380a5f7 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -41,6 +41,10 @@
     ChildNodeInsertionNotifier(shadowHost).notify(shadowRoot.get());
     setNeedsDistributionRecalc();
 
+    // addShadowRoot() affects apply-author-styles. However, we know that the youngest shadow root has not had any children yet.
+    // The youngest shadow root's apply-author-styles is default (false). So we can just set m_applyAuthorStyles false.
+    m_applyAuthorStyles = false;
+
     if (shadowHost->attached())
         shadowHost->lazyReattach();
 
@@ -109,4 +113,37 @@
     clearDistribution();
 }
 
+bool ElementShadow::didAffectApplyAuthorStyles()
+{
+    bool applyAuthorStyles = resolveApplyAuthorStyles();
+
+    if (m_applyAuthorStyles == applyAuthorStyles)
+        return false;
+
+    m_applyAuthorStyles = applyAuthorStyles;
+    return true;
+}
+
+bool ElementShadow::containsActiveStyles() const
+{
+    for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
+        if (root->hasScopedHTMLStyleChild())
+            return true;
+        if (!root->containsShadowElements())
+            return false;
+    }
+    return false;
+}
+
+bool ElementShadow::resolveApplyAuthorStyles() const
+{
+    for (const ShadowRoot* shadowRoot = youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
+        if (shadowRoot->applyAuthorStyles())
+            return true;
+        if (!shadowRoot->containsShadowElements())
+            break;
+    }
+    return false;
+}
+
 } // namespace
diff --git a/Source/core/dom/shadow/ElementShadow.h b/Source/core/dom/shadow/ElementShadow.h
index 7a73f87..3f16157 100644
--- a/Source/core/dom/shadow/ElementShadow.h
+++ b/Source/core/dom/shadow/ElementShadow.h
@@ -55,6 +55,7 @@
     ElementShadow* containingShadow() const;
 
     ShadowRoot* addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType);
+    bool applyAuthorStyles() const { return m_applyAuthorStyles; }
 
     void attach(const Node::AttachContext&);
     void detach(const Node::AttachContext&);
@@ -79,16 +80,22 @@
 
     void setNeedsDistributionRecalc();
 
+    bool didAffectApplyAuthorStyles();
+    bool containsActiveStyles() const;
+
 private:
     ElementShadow()
         : m_needsDistributionRecalc(false)
+        , m_applyAuthorStyles(false)
     { }
 
     void removeAllShadowRoots();
+    bool resolveApplyAuthorStyles() const;
 
     DoublyLinkedList<ShadowRoot> m_shadowRoots;
     ContentDistributor m_distributor;
     bool m_needsDistributionRecalc;
+    bool m_applyAuthorStyles;
 };
 
 inline Element* ElementShadow::host() const
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
index e7e9e52..b4626d7 100644
--- a/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -140,6 +140,7 @@
             if (isActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope()->rootNode() == root) {
                 m_registeredWithShadowRoot = true;
                 root->ensureScopeDistribution()->registerInsertionPoint(this);
+                rootOwner->didAffectApplyAuthorStyles();
                 if (canAffectSelector())
                     rootOwner->willAffectSelector();
             }
@@ -170,8 +171,11 @@
         ASSERT(root);
         m_registeredWithShadowRoot = false;
         root->ensureScopeDistribution()->unregisterInsertionPoint(this);
-        if (rootOwner && canAffectSelector())
-            rootOwner->willAffectSelector();
+        if (rootOwner) {
+            rootOwner->didAffectApplyAuthorStyles();
+            if (canAffectSelector())
+                rootOwner->willAffectSelector();
+        }
     }
 
     HTMLElement::removedFrom(insertionPoint);
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index dba48d3..a218b17 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -162,9 +162,6 @@
 
     if (!attached()) {
         attach();
-        // attach recalculates the style for all children. No need to do it twice.
-        clearNeedsStyleRecalc();
-        clearChildNeedsStyleRecalc();
         return;
     }
 
@@ -219,6 +216,17 @@
     if (!isActive())
         return;
 
+    ASSERT(host());
+    ASSERT(host()->shadow());
+    if (host()->shadow()->didAffectApplyAuthorStyles())
+        host()->setNeedsStyleRecalc();
+
+    // Since styles in shadow trees can select shadow hosts, set shadow host's needs-recalc flag true.
+    // FIXME: host->setNeedsStyleRecalc() should take care of all elements in its shadow tree.
+    // However, when host's recalcStyle is skipped (i.e. host's parent has no renderer),
+    // no recalc style is invoked for any elements in its shadow tree.
+    // This problem occurs when using getComputedStyle() API.
+    // So currently host and shadow root's needsStyleRecalc flags are set to be true.
     setNeedsStyleRecalc();
 }
 
diff --git a/Source/core/dom/shadow/ShadowRoot.h b/Source/core/dom/shadow/ShadowRoot.h
index 2551fc6..3bfcc3d 100644
--- a/Source/core/dom/shadow/ShadowRoot.h
+++ b/Source/core/dom/shadow/ShadowRoot.h
@@ -60,9 +60,9 @@
 
     void recalcStyle(StyleChange);
 
-    virtual bool applyAuthorStyles() const OVERRIDE { return m_applyAuthorStyles; }
+    bool applyAuthorStyles() const { return m_applyAuthorStyles; }
     void setApplyAuthorStyles(bool);
-    virtual bool resetStyleInheritance() const OVERRIDE { return m_resetStyleInheritance; }
+    bool resetStyleInheritance() const { return m_resetStyleInheritance; }
     void setResetStyleInheritance(bool);
 
     Element* host() const { return toElement(parentOrShadowHostNode()); }
diff --git a/Source/core/dom/shadow/ShadowRoot.idl b/Source/core/dom/shadow/ShadowRoot.idl
index b659c7c..105c008 100644
--- a/Source/core/dom/shadow/ShadowRoot.idl
+++ b/Source/core/dom/shadow/ShadowRoot.idl
@@ -32,7 +32,7 @@
     attribute boolean resetStyleInheritance;
     [EnabledAtRuntime=ShadowDOM, ImplementedAs=bindingsOlderShadowRoot] readonly attribute ShadowRoot olderShadowRoot;
 
-    [TreatNullAs=NullString, DeliverCustomElementCallbacks, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds, SetterRaisesException] attribute DOMString innerHTML;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds, SetterRaisesException] attribute DOMString innerHTML;
 
     [RaisesException] Node cloneNode([Default=Undefined] optional boolean deep);
     Selection getSelection();
diff --git a/Source/core/html/canvas/Int16Array.idl b/Source/core/editing/CompositionUnderline.h
similarity index 68%
rename from Source/core/html/canvas/Int16Array.idl
rename to Source/core/editing/CompositionUnderline.h
index 350bcbb..5f97ac7 100644
--- a/Source/core/html/canvas/Int16Array.idl
+++ b/Source/core/editing/CompositionUnderline.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006, 2010 Apple Computer, Inc. All rights reserved.
+ * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,19 +23,24 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-[
-    GlobalContext=Window&WorkerGlobalScope,
-    ConstructorTemplate=TypedArray,
-    CustomToV8,
-    DoNotCheckConstants
-] interface Int16Array : ArrayBufferView {
-    const unsigned long BYTES_PER_ELEMENT = 2;
+#ifndef CompositionUnderline_h
+#define CompositionUnderline_h
 
-    readonly attribute unsigned long length;
-    Int16Array subarray([Default=Undefined] optional long start,
-                        optional long end);
+#include "core/platform/graphics/Color.h"
 
-    // void set(Int16Array array, optional in unsigned long offset);
-    // void set(sequence<long> array, optional in unsigned long offset);
-    void set();
+namespace WebCore {
+
+struct CompositionUnderline {
+    CompositionUnderline()
+        : startOffset(0), endOffset(0), thick(false) { }
+    CompositionUnderline(unsigned s, unsigned e, const Color& c, bool t)
+        : startOffset(s), endOffset(e), color(c), thick(t) { }
+    unsigned startOffset;
+    unsigned endOffset;
+    Color color;
+    bool thick;
 };
+
+} // namespace WebCore
+
+#endif // CompositionUnderline_h
diff --git a/Source/core/editing/EditingStyle.cpp b/Source/core/editing/EditingStyle.cpp
index 7211fc1..614038c 100644
--- a/Source/core/editing/EditingStyle.cpp
+++ b/Source/core/editing/EditingStyle.cpp
@@ -58,16 +58,10 @@
 
 // Editing style properties must be preserved during editing operation.
 // e.g. when a user inserts a new paragraph, all properties listed here must be copied to the new paragraph.
-// NOTE: Use editingProperties() to respect runtime enabling of properties.
-static const unsigned nonInheritedStaticPropertiesCount = 2;
-
+// NOTE: Use either allEditingProperties() or inheritableEditingProperties() to
+// respect runtime enabling of properties.
 static const CSSPropertyID staticEditingProperties[] = {
-    // NOTE: inheritableEditingProperties depends on these two properties being first.
-    // If you change this list, make sure to update nonInheritedPropertyCount.
     CSSPropertyBackgroundColor,
-    CSSPropertyTextDecoration,
-
-    // CSS inheritable properties
     CSSPropertyColor,
     CSSPropertyFontFamily,
     CSSPropertyFontSize,
@@ -78,6 +72,7 @@
     CSSPropertyLineHeight,
     CSSPropertyOrphans,
     CSSPropertyTextAlign,
+    CSSPropertyTextDecoration,
     CSSPropertyTextIndent,
     CSSPropertyTextTransform,
     CSSPropertyWhiteSpace,
@@ -102,8 +97,16 @@
 static const Vector<CSSPropertyID>& inheritableEditingProperties()
 {
     DEFINE_STATIC_LOCAL(Vector<CSSPropertyID>, properties, ());
-    if (properties.isEmpty())
-        RuntimeCSSEnabled::filterEnabledCSSPropertiesIntoVector(staticEditingProperties + nonInheritedStaticPropertiesCount, WTF_ARRAY_LENGTH(staticEditingProperties) - nonInheritedStaticPropertiesCount, properties);
+    if (properties.isEmpty()) {
+        RuntimeCSSEnabled::filterEnabledCSSPropertiesIntoVector(staticEditingProperties, WTF_ARRAY_LENGTH(staticEditingProperties), properties);
+        for (size_t index = 0; index < properties.size();) {
+            if (!CSSProperty::isInheritedProperty(properties[index])) {
+                properties.remove(index);
+                continue;
+            }
+            ++index;
+        }
+    }
     return properties;
 }
 
@@ -219,7 +222,7 @@
     RefPtr<CSSValue> styleValue = style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect);
     if (!styleValue)
         styleValue = style->getPropertyCSSValue(CSSPropertyTextDecoration);
-    return matches(element) && styleValue && styleValue->isValueList() && static_cast<CSSValueList*>(styleValue.get())->hasValue(m_primitiveValue.get());
+    return matches(element) && styleValue && styleValue->isValueList() && toCSSValueList(styleValue.get())->hasValue(m_primitiveValue.get());
 }
 
 class HTMLAttributeEquivalent : public HTMLElementEquivalent {
@@ -367,7 +370,7 @@
     if (!colorValue || !colorValue->isPrimitiveValue())
         return Color::transparent;
 
-    CSSPrimitiveValue* primitiveColor = static_cast<CSSPrimitiveValue*>(colorValue);
+    CSSPrimitiveValue* primitiveColor = toCSSPrimitiveValue(colorValue);
     if (primitiveColor->isRGBColor())
         return primitiveColor->getRGBA32Value();
 
@@ -498,7 +501,7 @@
     if (!value || !value->isPrimitiveValue())
         return;
 
-    CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value.get());
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
 
     // Only PX handled now. If we handle more types in the future, perhaps
     // a switch statement here would be more appropriate.
@@ -636,12 +639,6 @@
         m_mutableStyle->removeProperty(nodeStyle->propertyAt(i).id());
 }
 
-void EditingStyle::removeNonEditingProperties()
-{
-    if (m_mutableStyle)
-        m_mutableStyle = copyEditingProperties(m_mutableStyle.get());
-}
-
 void EditingStyle::collapseTextDecorationProperties()
 {
     if (!m_mutableStyle)
@@ -1000,11 +997,28 @@
         && (mode == EditingStyle::OverrideValues || !equivalent->propertyExistsInStyle(style));
 }
 
+static PassRefPtr<MutableStylePropertySet> extractEditingProperties(const StylePropertySet* style, EditingStyle::PropertiesToInclude propertiesToInclude)
+{
+    if (!style)
+        return 0;
+
+    switch (propertiesToInclude) {
+    case EditingStyle::AllProperties:
+    case EditingStyle::EditingPropertiesInEffect:
+        return copyEditingProperties(style, AllEditingProperties);
+    case EditingStyle::OnlyEditingInheritableProperties:
+        return copyEditingProperties(style, OnlyInheritableEditingProperties);
+    }
+
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
 void EditingStyle::mergeInlineAndImplicitStyleOfElement(Element* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude)
 {
     RefPtr<EditingStyle> styleFromRules = EditingStyle::create();
     styleFromRules->mergeStyleFromRulesForSerialization(element);
-    styleFromRules->removeNonEditingProperties();
+    styleFromRules->m_mutableStyle = extractEditingProperties(styleFromRules->m_mutableStyle.get(), propertiesToInclude);
     mergeStyle(styleFromRules->m_mutableStyle.get(), mode);
 
     mergeInlineStyleOfElement(element, mode, propertiesToInclude);
@@ -1085,7 +1099,7 @@
         // text decorations never override values
         if ((property.id() == CSSPropertyTextDecoration || property.id() == CSSPropertyWebkitTextDecorationsInEffect) && property.value()->isValueList() && value) {
             if (value->isValueList()) {
-                mergeTextDecorationValues(static_cast<CSSValueList*>(value.get()), static_cast<CSSValueList*>(property.value()));
+                mergeTextDecorationValues(toCSSValueList(value.get()), toCSSValueList(property.value()));
                 continue;
             }
             value = 0; // text-decoration: none is equivalent to not having the property
@@ -1139,7 +1153,7 @@
             CSSValue* value = property.value();
             if (!value->isPrimitiveValue())
                 continue;
-            if (static_cast<CSSPrimitiveValue*>(value)->isPercentage()) {
+            if (toCSSPrimitiveValue(value)->isPercentage()) {
                 if (RefPtr<CSSValue> computedPropertyValue = computedStyleForElement->getPropertyCSSValue(property.id()))
                     fromComputedStyle->addParsedProperty(CSSProperty(property.id(), computedPropertyValue));
             }
@@ -1212,7 +1226,7 @@
     RefPtr<CSSValue> cssValue = m_mutableStyle->getPropertyCSSValue(CSSPropertyFontSize);
     if (!cssValue || !cssValue->isPrimitiveValue())
         return 0;
-    return legacyFontSizeFromCSSValue(document, static_cast<CSSPrimitiveValue*>(cssValue.get()),
+    return legacyFontSizeFromCSSValue(document, toCSSPrimitiveValue(cssValue.get()),
         m_shouldUseFixedDefaultFontSize, AlwaysUseLegacyFontSize);
 }
 
@@ -1418,7 +1432,7 @@
         DEFINE_STATIC_LOCAL(RefPtr<CSSPrimitiveValue>, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
         DEFINE_STATIC_LOCAL(RefPtr<CSSPrimitiveValue>, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
 
-        RefPtr<CSSValueList> newTextDecoration = static_cast<CSSValueList*>(textDecoration.get())->copy();
+        RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
         if (newTextDecoration->removeAll(underline.get()))
             m_applyUnderline = true;
         if (newTextDecoration->removeAll(lineThrough.get()))
@@ -1453,7 +1467,7 @@
     if (RefPtr<CSSValue> fontSize = style->getPropertyCSSValue(CSSPropertyFontSize)) {
         if (!fontSize->isPrimitiveValue())
             style->removeProperty(CSSPropertyFontSize); // Can't make sense of the number. Put no font size.
-        else if (int legacyFontSize = legacyFontSizeFromCSSValue(document, static_cast<CSSPrimitiveValue*>(fontSize.get()),
+        else if (int legacyFontSize = legacyFontSizeFromCSSValue(document, toCSSPrimitiveValue(fontSize.get()),
                 shouldUseFixedFontDefaultSize, UseLegacyFontSizeOnlyIfPixelValuesMatch)) {
             m_applyFontSize = String::number(legacyFontSize);
             style->removeProperty(CSSPropertyFontSize);
@@ -1467,8 +1481,8 @@
     if (!textDecoration || !textDecoration->isValueList() || !refTextDecoration || !refTextDecoration->isValueList())
         return;
 
-    RefPtr<CSSValueList> newTextDecoration = static_cast<CSSValueList*>(textDecoration.get())->copy();
-    CSSValueList* valuesInRefTextDecoration = static_cast<CSSValueList*>(refTextDecoration);
+    RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
+    CSSValueList* valuesInRefTextDecoration = toCSSValueList(refTextDecoration);
 
     for (size_t i = 0; i < valuesInRefTextDecoration->length(); i++)
         newTextDecoration->removeAll(valuesInRefTextDecoration->item(i));
diff --git a/Source/core/editing/EditingStyle.h b/Source/core/editing/EditingStyle.h
index b56a7bc..fbfa6e8 100644
--- a/Source/core/editing/EditingStyle.h
+++ b/Source/core/editing/EditingStyle.h
@@ -111,7 +111,6 @@
     void removeBlockProperties();
     void removeStyleAddedByNode(Node*);
     void removeStyleConflictingWithStyleOfNode(Node*);
-    void removeNonEditingProperties();
     void collapseTextDecorationProperties();
     enum ShouldIgnoreTextOnlyProperties { IgnoreTextOnlyProperties, DoNotIgnoreTextOnlyProperties };
     TriState triStateOfStyle(EditingStyle*) const;
diff --git a/Source/core/editing/Editor.cpp b/Source/core/editing/Editor.cpp
index 1534ca3..5931025 100644
--- a/Source/core/editing/Editor.cpp
+++ b/Source/core/editing/Editor.cpp
@@ -35,7 +35,6 @@
 #include "core/css/StylePropertySet.h"
 #include "core/dom/Clipboard.h"
 #include "core/dom/ClipboardEvent.h"
-#include "core/dom/CompositionEvent.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/DocumentMarkerController.h"
 #include "core/dom/EventNames.h"
@@ -44,10 +43,10 @@
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Text.h"
 #include "core/dom/TextEvent.h"
-#include "core/dom/UserTypingGestureIndicator.h"
 #include "core/editing/ApplyStyleCommand.h"
 #include "core/editing/DeleteSelectionCommand.h"
 #include "core/editing/IndentOutdentCommand.h"
+#include "core/editing/InputMethodController.h"
 #include "core/editing/InsertListCommand.h"
 #include "core/editing/ModifySelectionListLevel.h"
 #include "core/editing/RemoveFormatCommand.h"
@@ -88,6 +87,20 @@
 using namespace WTF;
 using namespace Unicode;
 
+Editor::RevealSelectionScope::RevealSelectionScope(Editor* editor)
+    : m_editor(editor)
+{
+    ++m_editor->m_preventRevealSelection;
+}
+
+Editor::RevealSelectionScope::~RevealSelectionScope()
+{
+    ASSERT(m_editor->m_preventRevealSelection);
+    --m_editor->m_preventRevealSelection;
+    if (!m_editor->m_preventRevealSelection)
+        m_editor->m_frame->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
+}
+
 namespace {
 
 bool isSelectionInTextField(const VisibleSelection& selection)
@@ -784,7 +797,7 @@
 
 Editor::Editor(Frame* frame)
     : FrameDestructionObserver(frame)
-    , m_ignoreCompositionSelectionChange(false)
+    , m_preventRevealSelection(0)
     , m_shouldStartNewKillRingSequence(false)
     // This is off by default, since most editors want this behavior (this matches IE but not FF).
     , m_shouldStyleWithCSS(false)
@@ -802,8 +815,7 @@
 
 void Editor::clear()
 {
-    m_compositionNode = 0;
-    m_customCompositionUnderlines.clear();
+    m_frame->inputMethodController().clear();
     m_shouldStyleWithCSS = false;
     m_defaultParagraphSeparator = EditorParagraphSeparatorIsDiv;
 }
@@ -813,11 +825,6 @@
     return m_frame->eventHandler()->handleTextInputEvent(text, triggeringEvent);
 }
 
-bool Editor::insertTextForConfirmedComposition(const String& text)
-{
-    return m_frame->eventHandler()->handleTextInputEvent(text, 0, TextEventInputComposition);
-}
-
 bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
 {
     if (text.isEmpty())
@@ -849,9 +856,10 @@
             TypingCommand::insertText(document.get(), text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionConfirm : TypingCommand::TextCompositionNone);
 
             // Reveal the current selection
-            if (Frame* editedFrame = document->frame())
+            if (Frame* editedFrame = document->frame()) {
                 if (Page* page = editedFrame->page())
-                    page->focusController()->focusedOrMainFrame()->selection()->revealSelection(ScrollAlignment::alignCenterIfNeeded);
+                    page->focusController().focusedOrMainFrame()->selection()->revealSelection(ScrollAlignment::alignCenterIfNeeded);
+            }
         }
     }
 
@@ -905,7 +913,7 @@
     if (shouldDeleteRange(selection.get())) {
         updateMarkersForWordsAffectedByEditing(true);
         if (enclosingTextFormControl(m_frame->selection()->start())) {
-            Pasteboard::generalPasteboard()->writePlainText(selectedTextForClipboard(),
+            Pasteboard::generalPasteboard()->writePlainText(m_frame->selectedTextForClipboard(),
                 canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
         } else
             Pasteboard::generalPasteboard()->writeSelection(selection.get(), canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForClipboard);
@@ -923,7 +931,7 @@
     }
 
     if (enclosingTextFormControl(m_frame->selection()->start())) {
-        Pasteboard::generalPasteboard()->writePlainText(selectedTextForClipboard(),
+        Pasteboard::generalPasteboard()->writePlainText(m_frame->selectedTextForClipboard(),
             canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
     } else {
         Document* document = m_frame->document();
@@ -1123,194 +1131,6 @@
     return result;
 }
 
-void Editor::selectComposition()
-{
-    RefPtr<Range> range = compositionRange();
-    if (!range)
-        return;
-
-    // The composition can start inside a composed character sequence, so we have to override checks.
-    // See <http://bugs.webkit.org/show_bug.cgi?id=15781>
-    VisibleSelection selection;
-    selection.setWithoutValidation(range->startPosition(), range->endPosition());
-    m_frame->selection()->setSelection(selection, 0);
-}
-
-void Editor::confirmComposition()
-{
-    if (!m_compositionNode)
-        return;
-    finishComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
-}
-
-void Editor::confirmComposition(const String& text)
-{
-    finishComposition(text, ConfirmComposition);
-}
-
-void Editor::cancelComposition()
-{
-    if (!m_compositionNode)
-        return;
-    finishComposition(emptyString(), CancelComposition);
-}
-
-void Editor::cancelCompositionIfSelectionIsInvalid()
-{
-    if (!hasComposition() || ignoreCompositionSelectionChange())
-        return;
-
-    // Check if selection start and selection end are valid.
-    Position start = m_frame->selection()->start();
-    Position end = m_frame->selection()->end();
-    if (start.containerNode() == m_compositionNode
-        && end.containerNode() == m_compositionNode
-        && static_cast<unsigned>(start.computeOffsetInContainerNode()) > m_compositionStart
-        && static_cast<unsigned>(end.computeOffsetInContainerNode()) < m_compositionEnd)
-        return;
-
-    cancelComposition();
-    if (client())
-        client()->didCancelCompositionOnSelectionChange();
-}
-
-void Editor::finishComposition(const String& text, FinishCompositionMode mode)
-{
-    ASSERT(mode == ConfirmComposition || mode == CancelComposition);
-    UserTypingGestureIndicator typingGestureIndicator(m_frame);
-
-    setIgnoreCompositionSelectionChange(true);
-
-    if (mode == CancelComposition)
-        ASSERT(text == emptyString());
-    else
-        selectComposition();
-
-    if (m_frame->selection()->isNone()) {
-        setIgnoreCompositionSelectionChange(false);
-        return;
-    }
-
-    // Dispatch a compositionend event to the focused node.
-    // We should send this event before sending a TextEvent as written in Section 6.2.2 and 6.2.3 of
-    // the DOM Event specification.
-    if (Element* target = m_frame->document()->focusedElement()) {
-        RefPtr<CompositionEvent> event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
-        target->dispatchEvent(event, IGNORE_EXCEPTION);
-    }
-
-    // If text is empty, then delete the old composition here.  If text is non-empty, InsertTextCommand::input
-    // will delete the old composition with an optimized replace operation.
-    if (text.isEmpty() && mode != CancelComposition)
-        TypingCommand::deleteSelection(m_frame->document(), 0);
-
-    m_compositionNode = 0;
-    m_customCompositionUnderlines.clear();
-
-    insertTextForConfirmedComposition(text);
-
-    if (mode == CancelComposition) {
-        // An open typing command that disagrees about current selection would cause issues with typing later on.
-        TypingCommand::closeTyping(m_frame);
-    }
-
-    setIgnoreCompositionSelectionChange(false);
-}
-
-void Editor::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, unsigned selectionStart, unsigned selectionEnd)
-{
-    UserTypingGestureIndicator typingGestureIndicator(m_frame);
-
-    setIgnoreCompositionSelectionChange(true);
-
-    // Updates styles before setting selection for composition to prevent
-    // inserting the previous composition text into text nodes oddly.
-    // See https://bugs.webkit.org/show_bug.cgi?id=46868
-    m_frame->document()->updateStyleIfNeeded();
-
-    selectComposition();
-
-    if (m_frame->selection()->isNone()) {
-        setIgnoreCompositionSelectionChange(false);
-        return;
-    }
-
-    if (Element* target = m_frame->document()->focusedElement()) {
-        // Dispatch an appropriate composition event to the focused node.
-        // We check the composition status and choose an appropriate composition event since this
-        // function is used for three purposes:
-        // 1. Starting a new composition.
-        //    Send a compositionstart and a compositionupdate event when this function creates
-        //    a new composition node, i.e.
-        //    m_compositionNode == 0 && !text.isEmpty().
-        //    Sending a compositionupdate event at this time ensures that at least one
-        //    compositionupdate event is dispatched.
-        // 2. Updating the existing composition node.
-        //    Send a compositionupdate event when this function updates the existing composition
-        //    node, i.e. m_compositionNode != 0 && !text.isEmpty().
-        // 3. Canceling the ongoing composition.
-        //    Send a compositionend event when function deletes the existing composition node, i.e.
-        //    m_compositionNode != 0 && test.isEmpty().
-        RefPtr<CompositionEvent> event;
-        if (!m_compositionNode) {
-            // We should send a compositionstart event only when the given text is not empty because this
-            // function doesn't create a composition node when the text is empty.
-            if (!text.isEmpty()) {
-                target->dispatchEvent(CompositionEvent::create(eventNames().compositionstartEvent, m_frame->domWindow(), selectedText()));
-                event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->domWindow(), text);
-            }
-        } else {
-            if (!text.isEmpty())
-                event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->domWindow(), text);
-            else
-                event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
-        }
-        if (event.get())
-            target->dispatchEvent(event, IGNORE_EXCEPTION);
-    }
-
-    // If text is empty, then delete the old composition here.  If text is non-empty, InsertTextCommand::input
-    // will delete the old composition with an optimized replace operation.
-    if (text.isEmpty())
-        TypingCommand::deleteSelection(m_frame->document(), TypingCommand::PreventSpellChecking);
-
-    m_compositionNode = 0;
-    m_customCompositionUnderlines.clear();
-
-    if (!text.isEmpty()) {
-        TypingCommand::insertText(m_frame->document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
-
-        // Find out what node has the composition now.
-        Position base = m_frame->selection()->base().downstream();
-        Position extent = m_frame->selection()->extent();
-        Node* baseNode = base.deprecatedNode();
-        unsigned baseOffset = base.deprecatedEditingOffset();
-        Node* extentNode = extent.deprecatedNode();
-        unsigned extentOffset = extent.deprecatedEditingOffset();
-
-        if (baseNode && baseNode == extentNode && baseNode->isTextNode() && baseOffset + text.length() == extentOffset) {
-            m_compositionNode = toText(baseNode);
-            m_compositionStart = baseOffset;
-            m_compositionEnd = extentOffset;
-            m_customCompositionUnderlines = underlines;
-            size_t numUnderlines = m_customCompositionUnderlines.size();
-            for (size_t i = 0; i < numUnderlines; ++i) {
-                m_customCompositionUnderlines[i].startOffset += baseOffset;
-                m_customCompositionUnderlines[i].endOffset += baseOffset;
-            }
-            if (baseNode->renderer())
-                baseNode->renderer()->repaint();
-
-            unsigned start = min(baseOffset + selectionStart, extentOffset);
-            unsigned end = min(max(start, baseOffset + selectionEnd), extentOffset);
-            RefPtr<Range> selectedRange = Range::create(baseNode->document(), baseNode, start, baseNode, end);
-            m_frame->selection()->setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
-        }
-    }
-
-    setIgnoreCompositionSelectionChange(false);
-}
-
 void Editor::ignoreSpelling()
 {
     if (!client())
@@ -1887,34 +1707,12 @@
 
 void Editor::revealSelectionAfterEditingOperation(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)
 {
-    if (m_ignoreCompositionSelectionChange)
+    if (m_preventRevealSelection)
         return;
 
     m_frame->selection()->revealSelection(alignment, revealExtentOption);
 }
 
-void Editor::setIgnoreCompositionSelectionChange(bool ignore)
-{
-    if (m_ignoreCompositionSelectionChange == ignore)
-        return;
-
-    m_ignoreCompositionSelectionChange = ignore;
-    if (!ignore)
-        revealSelectionAfterEditingOperation(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
-}
-
-PassRefPtr<Range> Editor::compositionRange() const
-{
-    if (!m_compositionNode)
-        return 0;
-    unsigned length = m_compositionNode->length();
-    unsigned start = min(m_compositionStart, length);
-    unsigned end = min(max(start, m_compositionEnd), length);
-    if (start >= end)
-        return 0;
-    return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
-}
-
 bool Editor::setSelectionOffsets(int selectionStart, int selectionEnd)
 {
     Element* rootEditableElement = m_frame->selection()->rootEditableElement();
@@ -2008,24 +1806,6 @@
         client()->respondToChangedSelection(m_frame);
 }
 
-String Editor::selectedText() const
-{
-    return selectedText(TextIteratorDefaultBehavior);
-}
-
-String Editor::selectedTextForClipboard() const
-{
-    if (m_frame->settings() && m_frame->settings()->selectionIncludesAltImageText())
-        return selectedText(TextIteratorEmitsImageAltText);
-    return selectedText();
-}
-
-String Editor::selectedText(TextIteratorBehavior behavior) const
-{
-    // We remove '\0' characters because they are not visibly rendered to the user.
-    return plainText(m_frame->selection()->toNormalizedRange().get(), behavior).replace(0, "");
-}
-
 IntRect Editor::firstRectForRange(Range* range) const
 {
     LayoutUnit extraWidthToEndOfLine = 0;
@@ -2291,15 +2071,7 @@
             && oldSelection.start().deprecatedNode()
             && oldSelection.start().anchorNode()->inDocument()
             && !isSelectionInTextField(oldSelection)) {
-            VisiblePosition oldStart(oldSelection.visibleStart());
-            VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
-            if (oldAdjacentWords != newAdjacentWords) {
-                if (isContinuousGrammarCheckingEnabled) {
-                    VisibleSelection oldSelectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
-                    markMisspellingsAndBadGrammar(oldAdjacentWords, oldSelectedSentence != newSelectedSentence, oldSelectedSentence);
-                } else
-                    markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
-            }
+            spellCheckOldSelection(oldSelection, newAdjacentWords, newSelectedSentence);
         }
 
         if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)) {
@@ -2318,11 +2090,39 @@
     if (!isContinuousGrammarCheckingEnabled)
         m_frame->document()->markers()->removeMarkers(DocumentMarker::Grammar);
 
-    cancelCompositionIfSelectionIsInvalid();
+    m_frame->inputMethodController().cancelCompositionIfSelectionIsInvalid();
 
     notifyComponentsOnChangedSelection(oldSelection, options);
 }
 
+void Editor::spellCheckAfterBlur()
+{
+    if (!m_frame->selection()->selection().isContentEditable())
+        return;
+
+    if (isSelectionInTextField(m_frame->selection()->selection())) {
+        // textFieldDidEndEditing() and textFieldDidBeginEditing() handle this.
+        return;
+    }
+
+    VisibleSelection empty;
+    spellCheckOldSelection(m_frame->selection()->selection(), empty, empty);
+}
+
+void Editor::spellCheckOldSelection(const VisibleSelection& oldSelection, const VisibleSelection& newAdjacentWords, const VisibleSelection& newSelectedSentence)
+{
+    VisiblePosition oldStart(oldSelection.visibleStart());
+    VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
+    if (oldAdjacentWords  != newAdjacentWords) {
+        if (isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled()) {
+            VisibleSelection selectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
+            markMisspellingsAndBadGrammar(oldAdjacentWords, selectedSentence != newSelectedSentence, selectedSentence);
+        } else {
+            markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
+        }
+    }
+}
+
 static Node* findFirstMarkable(Node* node)
 {
     while (node) {
diff --git a/Source/core/editing/Editor.h b/Source/core/editing/Editor.h
index 60cd398..7fabdd4 100644
--- a/Source/core/editing/Editor.h
+++ b/Source/core/editing/Editor.h
@@ -37,7 +37,6 @@
 #include "core/editing/VisibleSelection.h"
 #include "core/editing/WritingDirection.h"
 #include "core/page/FrameDestructionObserver.h"
-#include "core/platform/graphics/Color.h"
 #include "core/platform/text/TextChecking.h"
 
 namespace WebCore {
@@ -63,17 +62,6 @@
 class TextEvent;
 struct TextCheckingResult;
 
-struct CompositionUnderline {
-    CompositionUnderline()
-        : startOffset(0), endOffset(0), thick(false) { }
-    CompositionUnderline(unsigned s, unsigned e, const Color& c, bool t)
-        : startOffset(s), endOffset(e), color(c), thick(t) { }
-    unsigned startOffset;
-    unsigned endOffset;
-    Color color;
-    bool thick;
-};
-
 enum EditorCommandSource { CommandFromMenuOrKeyBinding, CommandFromDOM, CommandFromDOMWithUserInterface };
 enum EditorParagraphSeparator { EditorParagraphSeparatorIsDiv, EditorParagraphSeparatorIsP };
 
@@ -192,7 +180,6 @@
     static bool commandIsSupportedFromMenuOrKeyBinding(const String& commandName); // Works without a frame.
 
     bool insertText(const String&, Event* triggeringEvent);
-    bool insertTextForConfirmedComposition(const String& text);
     bool insertTextWithoutSendingTextEvent(const String&, bool selectInsertedText, TextEvent* triggeringEvent);
     bool insertLineBreak();
     bool insertParagraphSeparator();
@@ -237,29 +224,9 @@
     bool smartInsertDeleteEnabled();
     bool isSelectTrailingWhitespaceEnabled();
 
-    // international text input composition
-    bool hasComposition() const { return m_compositionNode; }
-    void setComposition(const String&, const Vector<CompositionUnderline>&, unsigned selectionStart, unsigned selectionEnd);
-    // Inserts the text that is being composed as a regular text.
-    // This method does nothing if composition node is not present.
-    void confirmComposition();
-    // Inserts the given text string in the place of the existing composition, or replaces the selection if composition is not present.
-    void confirmComposition(const String& text);
-    // Deletes the existing composition text.
-    void cancelComposition();
-    void cancelCompositionIfSelectionIsInvalid();
-    PassRefPtr<Range> compositionRange() const;
     bool setSelectionOffsets(int selectionStart, int selectionEnd);
 
-    // getting international text input composition state (for use by InlineTextBox)
-    Text* compositionNode() const { return m_compositionNode.get(); }
-    unsigned compositionStart() const { return m_compositionStart; }
-    unsigned compositionEnd() const { return m_compositionEnd; }
-    bool compositionUsesCustomUnderlines() const { return !m_customCompositionUnderlines.isEmpty(); }
-    const Vector<CompositionUnderline>& customCompositionUnderlines() const { return m_customCompositionUnderlines; }
-
-    void setIgnoreCompositionSelectionChange(bool);
-    bool ignoreCompositionSelectionChange() const { return m_ignoreCompositionSelectionChange; }
+    bool preventRevealSelection() const { return m_preventRevealSelection; }
 
     void setStartNewKillRingSequence(bool);
 
@@ -287,10 +254,8 @@
     void clearMisspellingsAndBadGrammar(const VisibleSelection&);
     void markMisspellingsAndBadGrammar(const VisibleSelection&);
 
-    Node* findEventTargetFrom(const VisibleSelection& selection) const;
+    Node* findEventTargetFrom(const VisibleSelection&) const;
 
-    String selectedText() const;
-    String selectedTextForClipboard() const;
     bool findString(const String&, FindOptions);
     // FIXME: Switch callers over to the FindOptions version and retire this one.
     bool findString(const String&, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection);
@@ -310,6 +275,9 @@
     void respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions);
     bool shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity, bool stillSelecting) const;
 
+    void spellCheckAfterBlur();
+    void spellCheckOldSelection(const VisibleSelection& oldSelection, const VisibleSelection& newAdjacentWords, const VisibleSelection& newSelectedSentence);
+
     bool markedTextMatchesAreHighlighted() const;
     void setMarkedTextMatchesAreHighlighted(bool);
 
@@ -331,14 +299,20 @@
     EditorParagraphSeparator defaultParagraphSeparator() const { return m_defaultParagraphSeparator; }
     void setDefaultParagraphSeparator(EditorParagraphSeparator separator) { m_defaultParagraphSeparator = separator; }
 
+    class RevealSelectionScope {
+        WTF_MAKE_NONCOPYABLE(RevealSelectionScope);
+    public:
+        RevealSelectionScope(Editor*);
+        ~RevealSelectionScope();
+    private:
+        Editor* m_editor;
+    };
+    friend class RevealSelectionScope;
+
 private:
     RefPtr<CompositeEditCommand> m_lastEditCommand;
     RefPtr<Node> m_removedAnchor;
-    RefPtr<Text> m_compositionNode;
-    unsigned m_compositionStart;
-    unsigned m_compositionEnd;
-    Vector<CompositionUnderline> m_customCompositionUnderlines;
-    bool m_ignoreCompositionSelectionChange;
+    int m_preventRevealSelection;
     bool m_shouldStartNewKillRingSequence;
     bool m_shouldStyleWithCSS;
     OwnPtr<KillRing> m_killRing;
@@ -358,12 +332,6 @@
     void markMisspellingsOrBadGrammar(const VisibleSelection&, bool checkSpelling, RefPtr<Range>& firstMisspellingRange);
     TextCheckingTypeMask resolveTextCheckingTypeMask(TextCheckingTypeMask);
 
-    String selectedText(TextIteratorBehavior) const;
-
-    void selectComposition();
-    enum FinishCompositionMode { ConfirmComposition, CancelComposition };
-    void finishComposition(const String&, FinishCompositionMode);
-
     void changeSelectionAfterCommand(const VisibleSelection& newSelection, FrameSelection::SetSelectionOptions);
     void notifyComponentsOnChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions);
 
diff --git a/Source/core/editing/EditorCommand.cpp b/Source/core/editing/EditorCommand.cpp
index c295921..b32e2ff 100644
--- a/Source/core/editing/EditorCommand.cpp
+++ b/Source/core/editing/EditorCommand.cpp
@@ -139,9 +139,9 @@
         return false;
 
     RefPtr<CSSValue> selectedCSSValue = selectionStyle->style()->getPropertyCSSValue(propertyID);
-    String newStyle = ASCIILiteral("none");
+    String newStyle("none");
     if (selectedCSSValue->isValueList()) {
-        RefPtr<CSSValueList> selectedCSSValueList = static_cast<CSSValueList*>(selectedCSSValue.get());
+        RefPtr<CSSValueList> selectedCSSValueList = toCSSValueList(selectedCSSValue.get());
         if (!selectedCSSValueList->removeAll(value))
             selectedCSSValueList->append(value);
         if (selectedCSSValueList->length())
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index cefd25a..4aa52a2 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -37,7 +37,9 @@
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Range.h"
 #include "core/editing/Editor.h"
+#include "core/editing/InputMethodController.h"
 #include "core/editing/RenderedPosition.h"
+#include "core/editing/TextIterator.h"
 #include "core/editing/TypingCommand.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
@@ -90,7 +92,7 @@
     , m_absCaretBoundsDirty(true)
     , m_caretPaint(true)
     , m_isCaretBlinkingSuspended(false)
-    , m_focused(frame && frame->page() && frame->page()->focusController()->focusedFrame() == frame)
+    , m_focused(frame && frame->page() && frame->page()->focusController().focusedFrame() == frame)
     , m_shouldShowBlockCursor(false)
 {
     if (shouldAlwaysUseDirectionalSelection(m_frame))
@@ -261,7 +263,7 @@
 
     if (m_selection == s) {
         // Even if selection was not changed, selection offsets may have been changed.
-        m_frame->editor()->cancelCompositionIfSelectionIsInvalid();
+        m_frame->inputMethodController().cancelCompositionIfSelectionIsInvalid();
         notifyRendererOfSelectionChange(userTriggered);
         return;
     }
@@ -555,13 +557,11 @@
     return positionAfterCurrentWord;
 }
 
-#if ENABLE(USERSELECT_ALL)
 static void adjustPositionForUserSelectAll(VisiblePosition& pos, bool isForward)
 {
     if (Node* rootUserSelectAll = Position::rootUserSelectAllForNode(pos.deepEquivalent().anchorNode()))
         pos = isForward ? positionAfterNode(rootUserSelectAll).downstream(CanCrossEditingBoundary) : positionBeforeNode(rootUserSelectAll).upstream(CanCrossEditingBoundary);
 }
-#endif
 
 VisiblePosition FrameSelection::modifyExtendingRight(TextGranularity granularity)
 {
@@ -601,9 +601,7 @@
         pos = modifyExtendingForward(granularity);
         break;
     }
-#if ENABLE(USERSELECT_ALL)
     adjustPositionForUserSelectAll(pos, directionOfEnclosingBlock() == LTR);
-#endif
     return pos;
 }
 
@@ -643,9 +641,7 @@
             pos = endOfDocument(pos);
         break;
     }
-#if ENABLE(USERSELECT_ALL)
-     adjustPositionForUserSelectAll(pos, directionOfEnclosingBlock() == LTR);
-#endif
+    adjustPositionForUserSelectAll(pos, directionOfEnclosingBlock() == LTR);
     return pos;
 }
 
@@ -768,9 +764,7 @@
         pos = modifyExtendingBackward(granularity);
         break;
     }
-#if ENABLE(USERSELECT_ALL)
     adjustPositionForUserSelectAll(pos, !(directionOfEnclosingBlock() == LTR));
-#endif
     return pos;
 }
 
@@ -815,9 +809,7 @@
             pos = startOfDocument(pos);
         break;
     }
-#if ENABLE(USERSELECT_ALL)
     adjustPositionForUserSelectAll(pos, !(directionOfEnclosingBlock() == LTR));
-#endif
     return pos;
 }
 
@@ -1415,7 +1407,7 @@
     // Focus on the parent frame, and then select from before this element to after.
     VisibleSelection newSelection(beforeOwnerElement, afterOwnerElement);
     if (parent->selection()->shouldChangeSelection(newSelection)) {
-        page->focusController()->setFocusedFrame(parent);
+        page->focusController().setFocusedFrame(parent);
         parent->selection()->setSelection(newSelection);
     }
 }
@@ -1513,6 +1505,8 @@
     // Caret appears in the active frame.
     if (activeAndFocused)
         setSelectionFromNone();
+    else
+        m_frame->editor()->spellCheckAfterBlur();
     setCaretVisibility(activeAndFocused ? Visible : Hidden);
 
     // Update for caps lock state
@@ -1564,7 +1558,7 @@
 
 bool FrameSelection::isFocusedAndActive() const
 {
-    return m_focused && m_frame->page() && m_frame->page()->focusController()->isActive();
+    return m_focused && m_frame->page() && m_frame->page()->focusController().isActive();
 }
 
 inline static bool shouldStopBlinkingDueToTypingCommand(Frame* frame)
@@ -1716,7 +1710,7 @@
     bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
     if (caretBrowsing) {
         if (Element* anchor = enclosingAnchorElement(base())) {
-            m_frame->page()->focusController()->setFocusedElement(anchor, m_frame);
+            m_frame->page()->focusController().setFocusedElement(anchor, m_frame);
             return;
         }
     }
@@ -1728,7 +1722,7 @@
             // so add the !isFrameElement check here. There's probably a better way to make this
             // work in the long term, but this is the safest fix at this time.
             if (target->isMouseFocusable() && !isFrameElement(target)) {
-                m_frame->page()->focusController()->setFocusedElement(target, m_frame);
+                m_frame->page()->focusController().setFocusedElement(target, m_frame);
                 return;
             }
             target = target->parentOrShadowHostElement();
@@ -1737,7 +1731,7 @@
     }
 
     if (caretBrowsing)
-        m_frame->page()->focusController()->setFocusedElement(0, m_frame);
+        m_frame->page()->focusController().setFocusedElement(0, m_frame);
 }
 
 PassRefPtr<MutableStylePropertySet> FrameSelection::copyTypingStyle() const
@@ -1747,6 +1741,24 @@
     return m_typingStyle->style()->mutableCopy();
 }
 
+static String extractSelectedText(const FrameSelection& selection, TextIteratorBehavior behavior)
+{
+    // We remove '\0' characters because they are not visibly rendered to the user.
+    return plainText(selection.toNormalizedRange().get(), behavior).replace(0, "");
+}
+
+String FrameSelection::selectedText() const
+{
+    return extractSelectedText(*this, TextIteratorDefaultBehavior);
+}
+
+String FrameSelection::selectedTextForClipboard() const
+{
+    if (m_frame->settings() && m_frame->settings()->selectionIncludesAltImageText())
+        return extractSelectedText(*this, TextIteratorEmitsImageAltText);
+    return selectedText();
+}
+
 bool FrameSelection::shouldDeleteSelection(const VisibleSelection& selection) const
 {
     return m_frame->editor()->client()->shouldDeleteRange(selection.toNormalizedRange().get());
diff --git a/Source/core/editing/FrameSelection.h b/Source/core/editing/FrameSelection.h
index 8d352ca..d6c76f1 100644
--- a/Source/core/editing/FrameSelection.h
+++ b/Source/core/editing/FrameSelection.h
@@ -195,6 +195,9 @@
     void setTypingStyle(PassRefPtr<EditingStyle>);
     void clearTypingStyle();
 
+    String selectedText() const;
+    String selectedTextForClipboard() const;
+
     FloatRect bounds(bool clipToVisibleContent = true) const;
 
     void getClippedVisibleTextRectangles(Vector<FloatRect>&) const;
diff --git a/Source/core/editing/InputMethodController.cpp b/Source/core/editing/InputMethodController.cpp
new file mode 100644
index 0000000..606e331
--- /dev/null
+++ b/Source/core/editing/InputMethodController.cpp
@@ -0,0 +1,295 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/editing/InputMethodController.h"
+
+#include "core/dom/CompositionEvent.h"
+#include "core/dom/Document.h"
+#include "core/dom/Element.h"
+#include "core/dom/Range.h"
+#include "core/dom/Text.h"
+#include "core/dom/UserTypingGestureIndicator.h"
+#include "core/editing/Editor.h"
+#include "core/editing/TypingCommand.h"
+#include "core/page/EditorClient.h"
+#include "core/page/EventHandler.h"
+#include "core/page/Frame.h"
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+PassOwnPtr<InputMethodController> InputMethodController::create(Frame* frame)
+{
+    return adoptPtr(new InputMethodController(frame));
+}
+
+InputMethodController::InputMethodController(Frame* frame)
+    : m_frame(frame)
+    , m_compositionStart(0)
+    , m_compositionEnd(0)
+{
+}
+
+InputMethodController::~InputMethodController()
+{
+}
+
+inline Editor& InputMethodController::editor() const
+{
+    return *m_frame->editor();
+}
+
+inline EditorClient* InputMethodController::editorClient() const
+{
+    return editor().client();
+}
+
+void InputMethodController::clear()
+{
+    m_compositionNode = 0;
+    m_customCompositionUnderlines.clear();
+}
+
+bool InputMethodController::insertTextForConfirmedComposition(const String& text)
+{
+    return m_frame->eventHandler()->handleTextInputEvent(text, 0, TextEventInputComposition);
+}
+
+void InputMethodController::selectComposition() const
+{
+    RefPtr<Range> range = compositionRange();
+    if (!range)
+        return;
+
+    // The composition can start inside a composed character sequence, so we have to override checks.
+    // See <http://bugs.webkit.org/show_bug.cgi?id=15781>
+    VisibleSelection selection;
+    selection.setWithoutValidation(range->startPosition(), range->endPosition());
+    m_frame->selection()->setSelection(selection, 0);
+}
+
+void InputMethodController::confirmComposition()
+{
+    if (!m_compositionNode)
+        return;
+    finishComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
+}
+
+void InputMethodController::confirmComposition(const String& text)
+{
+    finishComposition(text, ConfirmComposition);
+}
+
+void InputMethodController::confirmCompositionAndResetState()
+{
+    if (!hasComposition())
+        return;
+
+    // We should verify the parent node of this IME composition node are
+    // editable because JavaScript may delete a parent node of the composition
+    // node. In this case, WebKit crashes while deleting texts from the parent
+    // node, which doesn't exist any longer.
+    RefPtr<Range> range = compositionRange();
+    if (range) {
+        Node* node = range->startContainer();
+        if (!node || !node->isContentEditable())
+            return;
+    }
+
+    // EditorClient::willSetInputMethodState() resets input method and the composition string is committed.
+    if (EditorClient* client = editorClient())
+        client->willSetInputMethodState();
+}
+
+void InputMethodController::cancelComposition()
+{
+    if (!m_compositionNode)
+        return;
+    finishComposition(emptyString(), CancelComposition);
+}
+
+void InputMethodController::cancelCompositionIfSelectionIsInvalid()
+{
+    if (!hasComposition() || editor().preventRevealSelection())
+        return;
+
+    // Check if selection start and selection end are valid.
+    Position start = m_frame->selection()->start();
+    Position end = m_frame->selection()->end();
+    if (start.containerNode() == m_compositionNode
+        && end.containerNode() == m_compositionNode
+        && static_cast<unsigned>(start.computeOffsetInContainerNode()) > m_compositionStart
+        && static_cast<unsigned>(end.computeOffsetInContainerNode()) < m_compositionEnd)
+        return;
+
+    cancelComposition();
+    if (editorClient())
+        editorClient()->didCancelCompositionOnSelectionChange();
+}
+
+void InputMethodController::finishComposition(const String& text, FinishCompositionMode mode)
+{
+    ASSERT(mode == ConfirmComposition || mode == CancelComposition);
+    UserTypingGestureIndicator typingGestureIndicator(m_frame);
+
+    Editor::RevealSelectionScope revealSelectionScope(&editor());
+
+    if (mode == CancelComposition)
+        ASSERT(text == emptyString());
+    else
+        selectComposition();
+
+    if (m_frame->selection()->isNone())
+        return;
+
+    // Dispatch a compositionend event to the focused node.
+    // We should send this event before sending a TextEvent as written in Section 6.2.2 and 6.2.3 of
+    // the DOM Event specification.
+    if (Element* target = m_frame->document()->focusedElement()) {
+        RefPtr<CompositionEvent> event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
+        target->dispatchEvent(event, IGNORE_EXCEPTION);
+    }
+
+    // If text is empty, then delete the old composition here. If text is non-empty, InsertTextCommand::input
+    // will delete the old composition with an optimized replace operation.
+    if (text.isEmpty() && mode != CancelComposition)
+        TypingCommand::deleteSelection(m_frame->document(), 0);
+
+    m_compositionNode = 0;
+    m_customCompositionUnderlines.clear();
+
+    insertTextForConfirmedComposition(text);
+
+    if (mode == CancelComposition) {
+        // An open typing command that disagrees about current selection would cause issues with typing later on.
+        TypingCommand::closeTyping(m_frame);
+    }
+}
+
+void InputMethodController::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, unsigned selectionStart, unsigned selectionEnd)
+{
+    UserTypingGestureIndicator typingGestureIndicator(m_frame);
+
+    Editor::RevealSelectionScope revealSelectionScope(&editor());
+
+    // Updates styles before setting selection for composition to prevent
+    // inserting the previous composition text into text nodes oddly.
+    // See https://bugs.webkit.org/show_bug.cgi?id=46868
+    m_frame->document()->updateStyleIfNeeded();
+
+    selectComposition();
+
+    if (m_frame->selection()->isNone())
+        return;
+
+    if (Element* target = m_frame->document()->focusedElement()) {
+        // Dispatch an appropriate composition event to the focused node.
+        // We check the composition status and choose an appropriate composition event since this
+        // function is used for three purposes:
+        // 1. Starting a new composition.
+        //    Send a compositionstart and a compositionupdate event when this function creates
+        //    a new composition node, i.e.
+        //    m_compositionNode == 0 && !text.isEmpty().
+        //    Sending a compositionupdate event at this time ensures that at least one
+        //    compositionupdate event is dispatched.
+        // 2. Updating the existing composition node.
+        //    Send a compositionupdate event when this function updates the existing composition
+        //    node, i.e. m_compositionNode != 0 && !text.isEmpty().
+        // 3. Canceling the ongoing composition.
+        //    Send a compositionend event when function deletes the existing composition node, i.e.
+        //    m_compositionNode != 0 && test.isEmpty().
+        RefPtr<CompositionEvent> event;
+        if (!m_compositionNode) {
+            // We should send a compositionstart event only when the given text is not empty because this
+            // function doesn't create a composition node when the text is empty.
+            if (!text.isEmpty()) {
+                target->dispatchEvent(CompositionEvent::create(eventNames().compositionstartEvent, m_frame->domWindow(), m_frame->selectedText()));
+                event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->domWindow(), text);
+            }
+        } else {
+            if (!text.isEmpty())
+                event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->domWindow(), text);
+            else
+                event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
+        }
+        if (event.get())
+            target->dispatchEvent(event, IGNORE_EXCEPTION);
+    }
+
+    // If text is empty, then delete the old composition here. If text is non-empty, InsertTextCommand::input
+    // will delete the old composition with an optimized replace operation.
+    if (text.isEmpty())
+        TypingCommand::deleteSelection(m_frame->document(), TypingCommand::PreventSpellChecking);
+
+    m_compositionNode = 0;
+    m_customCompositionUnderlines.clear();
+
+    if (!text.isEmpty()) {
+        TypingCommand::insertText(m_frame->document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
+
+        // Find out what node has the composition now.
+        Position base = m_frame->selection()->base().downstream();
+        Position extent = m_frame->selection()->extent();
+        Node* baseNode = base.deprecatedNode();
+        unsigned baseOffset = base.deprecatedEditingOffset();
+        Node* extentNode = extent.deprecatedNode();
+        unsigned extentOffset = extent.deprecatedEditingOffset();
+
+        if (baseNode && baseNode == extentNode && baseNode->isTextNode() && baseOffset + text.length() == extentOffset) {
+            m_compositionNode = toText(baseNode);
+            m_compositionStart = baseOffset;
+            m_compositionEnd = extentOffset;
+            m_customCompositionUnderlines = underlines;
+            size_t numUnderlines = m_customCompositionUnderlines.size();
+            for (size_t i = 0; i < numUnderlines; ++i) {
+                m_customCompositionUnderlines[i].startOffset += baseOffset;
+                m_customCompositionUnderlines[i].endOffset += baseOffset;
+            }
+            if (baseNode->renderer())
+                baseNode->renderer()->repaint();
+
+            unsigned start = std::min(baseOffset + selectionStart, extentOffset);
+            unsigned end = std::min(std::max(start, baseOffset + selectionEnd), extentOffset);
+            RefPtr<Range> selectedRange = Range::create(baseNode->document(), baseNode, start, baseNode, end);
+            m_frame->selection()->setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
+        }
+    }
+}
+
+PassRefPtr<Range> InputMethodController::compositionRange() const
+{
+    if (!m_compositionNode)
+        return 0;
+    unsigned length = m_compositionNode->length();
+    unsigned start = std::min(m_compositionStart, length);
+    unsigned end = std::min(std::max(start, m_compositionEnd), length);
+    if (start >= end)
+        return 0;
+    return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
+}
+
+} // namespace WebCore
diff --git a/Source/core/editing/InputMethodController.h b/Source/core/editing/InputMethodController.h
new file mode 100644
index 0000000..767f860
--- /dev/null
+++ b/Source/core/editing/InputMethodController.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef InputMethodController_h
+#define InputMethodController_h
+
+#include "core/editing/CompositionUnderline.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class Editor;
+class EditorClient;
+class Frame;
+class Range;
+class Text;
+
+class InputMethodController {
+public:
+    static PassOwnPtr<InputMethodController> create(Frame*);
+    ~InputMethodController();
+
+    // international text input composition
+    bool hasComposition() const { return m_compositionNode; }
+    void setComposition(const String&, const Vector<CompositionUnderline>&, unsigned selectionStart, unsigned selectionEnd);
+    // Inserts the text that is being composed as a regular text.
+    // This method does nothing if composition node is not present.
+    void confirmComposition();
+    // Inserts the given text string in the place of the existing composition, or replaces the selection if composition is not present.
+    void confirmComposition(const String& text);
+    void confirmCompositionAndResetState();
+    // Deletes the existing composition text.
+    void cancelComposition();
+    void cancelCompositionIfSelectionIsInvalid();
+    PassRefPtr<Range> compositionRange() const;
+
+    // getting international text input composition state (for use by InlineTextBox)
+    Text* compositionNode() const { return m_compositionNode.get(); }
+    unsigned compositionStart() const { return m_compositionStart; }
+    unsigned compositionEnd() const { return m_compositionEnd; }
+    bool compositionUsesCustomUnderlines() const { return !m_customCompositionUnderlines.isEmpty(); }
+    const Vector<CompositionUnderline>& customCompositionUnderlines() const { return m_customCompositionUnderlines; }
+
+    void clear();
+
+private:
+    Frame* m_frame;
+    RefPtr<Text> m_compositionNode;
+    unsigned m_compositionStart;
+    unsigned m_compositionEnd;
+    Vector<CompositionUnderline> m_customCompositionUnderlines;
+
+    explicit InputMethodController(Frame*);
+    Editor& editor() const;
+    EditorClient* editorClient() const;
+    bool insertTextForConfirmedComposition(const String& text);
+    void selectComposition() const;
+    enum FinishCompositionMode { ConfirmComposition, CancelComposition };
+    void finishComposition(const String&, FinishCompositionMode);
+};
+
+} // namespace WebCore
+
+#endif // InputMethodController_h
diff --git a/Source/core/editing/MarkupAccumulator.cpp b/Source/core/editing/MarkupAccumulator.cpp
index 6a4a5d0..cd5b7cf 100644
--- a/Source/core/editing/MarkupAccumulator.cpp
+++ b/Source/core/editing/MarkupAccumulator.cpp
@@ -48,11 +48,11 @@
 
 void MarkupAccumulator::appendCharactersReplacingEntities(StringBuilder& result, const String& source, unsigned offset, unsigned length, EntityMask entityMask)
 {
-    DEFINE_STATIC_LOCAL(const String, ampReference, (ASCIILiteral("&amp;")));
-    DEFINE_STATIC_LOCAL(const String, ltReference, (ASCIILiteral("&lt;")));
-    DEFINE_STATIC_LOCAL(const String, gtReference, (ASCIILiteral("&gt;")));
-    DEFINE_STATIC_LOCAL(const String, quotReference, (ASCIILiteral("&quot;")));
-    DEFINE_STATIC_LOCAL(const String, nbspReference, (ASCIILiteral("&nbsp;")));
+    DEFINE_STATIC_LOCAL(const String, ampReference, ("&amp;"));
+    DEFINE_STATIC_LOCAL(const String, ltReference, ("&lt;"));
+    DEFINE_STATIC_LOCAL(const String, gtReference, ("&gt;"));
+    DEFINE_STATIC_LOCAL(const String, quotReference, ("&quot;"));
+    DEFINE_STATIC_LOCAL(const String, nbspReference, ("&nbsp;"));
 
     static const EntityDescription entityMaps[] = {
         { '&', ampReference, EntityAmp },
@@ -256,14 +256,12 @@
     if (prefix.isEmpty())
         return !element->hasAttribute(xmlnsAtom);
 
-    DEFINE_STATIC_LOCAL(String, xmlnsWithColon, (ASCIILiteral("xmlns:")));
+    DEFINE_STATIC_LOCAL(String, xmlnsWithColon, ("xmlns:"));
     return !element->hasAttribute(xmlnsWithColon + prefix);
 }
 
 bool MarkupAccumulator::shouldAddNamespaceAttribute(const Attribute& attribute, Namespaces& namespaces)
 {
-    namespaces.checkConsistency();
-
     // Don't add namespace attributes twice
     if (attribute.name() == XMLNSNames::xmlnsAttr) {
         namespaces.set(emptyAtom.impl(), attribute.value().impl());
@@ -281,7 +279,6 @@
 
 void MarkupAccumulator::appendNamespace(StringBuilder& result, const AtomicString& prefix, const AtomicString& namespaceURI, Namespaces& namespaces)
 {
-    namespaces.checkConsistency();
     if (namespaceURI.isEmpty())
         return;
 
@@ -483,9 +480,6 @@
 
 void MarkupAccumulator::appendStartMarkup(StringBuilder& result, const Node* node, Namespaces* namespaces)
 {
-    if (namespaces)
-        namespaces->checkConsistency();
-
     switch (node->nodeType()) {
     case Node::TEXT_NODE:
         appendText(result, toText(const_cast<Node*>(node)));
diff --git a/Source/core/editing/ReplaceNodeWithSpanCommand.cpp b/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
index 3c262ae..1686ec0 100644
--- a/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
+++ b/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
@@ -52,16 +52,15 @@
 {
     ASSERT(nodeToReplace->inDocument());
     RefPtr<ContainerNode> parentNode = nodeToReplace->parentNode();
-    parentNode->insertBefore(newNode, nodeToReplace, ASSERT_NO_EXCEPTION);
 
+    // FIXME: Fix this to send the proper MutationRecords when MutationObservers are present.
+    newNode->cloneDataFromElement(*nodeToReplace);
     NodeVector children;
     getChildNodes(nodeToReplace, children);
     for (size_t i = 0; i < children.size(); ++i)
         newNode->appendChild(children[i], ASSERT_NO_EXCEPTION);
 
-    // FIXME: Fix this to send the proper MutationRecords when MutationObservers are present.
-    newNode->cloneDataFromElement(*nodeToReplace);
-
+    parentNode->insertBefore(newNode, nodeToReplace, ASSERT_NO_EXCEPTION);
     parentNode->removeChild(nodeToReplace, ASSERT_NO_EXCEPTION);
 }
 
diff --git a/Source/core/editing/SmartReplaceICU.cpp b/Source/core/editing/SmartReplaceICU.cpp
index fe13985..0d35e32 100644
--- a/Source/core/editing/SmartReplaceICU.cpp
+++ b/Source/core/editing/SmartReplaceICU.cpp
@@ -53,7 +53,7 @@
     if (!smartSet) {
         // Whitespace and newline (kCFCharacterSetWhitespaceAndNewline)
         UErrorCode ec = U_ZERO_ERROR;
-        String whitespaceAndNewline = ASCIILiteral("[[:WSpace:] [\\u000A\\u000B\\u000C\\u000D\\u0085]]");
+        String whitespaceAndNewline("[[:WSpace:] [\\u000A\\u000B\\u000C\\u000D\\u0085]]");
         smartSet = uset_openPattern(whitespaceAndNewline.charactersWithNullTermination().data(), whitespaceAndNewline.length(), &ec);
         ASSERT(U_SUCCESS(ec));
 
@@ -70,14 +70,14 @@
         uset_addRange(smartSet, 0x2F800, 0x2F800 + 0x021E); // CJK Compatibility Ideographs (0x2F800 - 0x2FA1D)
 
         if (isPreviousCharacter) {
-            addAllCodePoints(smartSet, ASCIILiteral("([\"\'#$/-`{"));
+            addAllCodePoints(smartSet, "([\"\'#$/-`{");
             preSmartSet = smartSet;
         } else {
-            addAllCodePoints(smartSet, ASCIILiteral(")].,;:?\'!\"%*-/}"));
+            addAllCodePoints(smartSet, ")].,;:?\'!\"%*-/}");
 
             // Punctuation (kCFCharacterSetPunctuation)
             UErrorCode ec = U_ZERO_ERROR;
-            String punctuationClass = ASCIILiteral("[:P:]");
+            String punctuationClass("[:P:]");
             USet* icuPunct = uset_openPattern(punctuationClass.charactersWithNullTermination().data(), punctuationClass.length(), &ec);
             ASSERT(U_SUCCESS(ec));
             uset_addAll(smartSet, icuPunct);
diff --git a/Source/core/editing/SpellCheckRequester.cpp b/Source/core/editing/SpellCheckRequester.cpp
new file mode 100644
index 0000000..af2ad11
--- /dev/null
+++ b/Source/core/editing/SpellCheckRequester.cpp
@@ -0,0 +1,262 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/editing/SpellCheckRequester.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/DocumentMarkerController.h"
+#include "core/dom/Node.h"
+#include "core/dom/Range.h"
+#include "core/editing/Editor.h"
+#include "core/page/EditorClient.h"
+#include "core/page/Frame.h"
+#include "core/page/Page.h"
+#include "core/page/Settings.h"
+#include "core/platform/text/TextCheckerClient.h"
+
+namespace WebCore {
+
+SpellCheckRequest::SpellCheckRequest(
+    PassRefPtr<Range> checkingRange,
+    PassRefPtr<Range> paragraphRange,
+    const String& text,
+    TextCheckingTypeMask mask,
+    TextCheckingProcessType processType,
+    const Vector<uint32_t>& documentMarkersInRange,
+    const Vector<unsigned>& documentMarkerOffsets)
+    : m_checker(0)
+    , m_checkingRange(checkingRange)
+    , m_paragraphRange(paragraphRange)
+    , m_rootEditableElement(m_checkingRange->startContainer()->rootEditableElement())
+    , m_requestData(unrequestedTextCheckingSequence, text, mask, processType, documentMarkersInRange, documentMarkerOffsets)
+{
+}
+
+SpellCheckRequest::~SpellCheckRequest()
+{
+}
+
+// static
+PassRefPtr<SpellCheckRequest> SpellCheckRequest::create(TextCheckingTypeMask textCheckingOptions, TextCheckingProcessType processType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange)
+{
+    ASSERT(checkingRange);
+    ASSERT(paragraphRange);
+
+    String text = checkingRange->text();
+    if (!text.length())
+        return PassRefPtr<SpellCheckRequest>();
+
+    const Vector<DocumentMarker*>& markers = checkingRange->ownerDocument()->markers()->markersInRange(checkingRange.get(), DocumentMarker::Spelling | DocumentMarker::Grammar);
+    Vector<uint32_t> hashes(markers.size());
+    Vector<unsigned> offsets(markers.size());
+    for (size_t i = 0; i < markers.size(); i++) {
+        hashes[i] = markers[i]->hash();
+        offsets[i] = markers[i]->startOffset();
+    }
+
+    return adoptRef(new SpellCheckRequest(checkingRange, paragraphRange, text, textCheckingOptions, processType, hashes, offsets));
+}
+
+const TextCheckingRequestData& SpellCheckRequest::data() const
+{
+    return m_requestData;
+}
+
+void SpellCheckRequest::didSucceed(const Vector<TextCheckingResult>& results)
+{
+    if (!m_checker)
+        return;
+    SpellChecker* checker = m_checker;
+    m_checker = 0;
+    checker->didCheckSucceed(m_requestData.sequence(), results);
+}
+
+void SpellCheckRequest::didCancel()
+{
+    if (!m_checker)
+        return;
+    SpellChecker* checker = m_checker;
+    m_checker = 0;
+    checker->didCheckCancel(m_requestData.sequence());
+}
+
+void SpellCheckRequest::setCheckerAndSequence(SpellChecker* requester, int sequence)
+{
+    ASSERT(!m_checker);
+    ASSERT(m_requestData.sequence() == unrequestedTextCheckingSequence);
+    m_checker = requester;
+    m_requestData.m_sequence = sequence;
+}
+
+void SpellCheckRequest::requesterDestroyed()
+{
+    m_checker = 0;
+}
+
+SpellChecker::SpellChecker(Frame* frame)
+    : m_frame(frame)
+    , m_lastRequestSequence(0)
+    , m_lastProcessedSequence(0)
+    , m_timerToProcessQueuedRequest(this, &SpellChecker::timerFiredToProcessQueuedRequest)
+{
+}
+
+SpellChecker::~SpellChecker()
+{
+    if (m_processingRequest)
+        m_processingRequest->requesterDestroyed();
+    for (RequestQueue::iterator i = m_requestQueue.begin(); i != m_requestQueue.end(); ++i)
+        (*i)->requesterDestroyed();
+}
+
+TextCheckerClient* SpellChecker::client() const
+{
+    Page* page = m_frame->page();
+    if (!page)
+        return 0;
+    return page->editorClient()->textChecker();
+}
+
+void SpellChecker::timerFiredToProcessQueuedRequest(Timer<SpellChecker>*)
+{
+    ASSERT(!m_requestQueue.isEmpty());
+    if (m_requestQueue.isEmpty())
+        return;
+
+    invokeRequest(m_requestQueue.takeFirst());
+}
+
+bool SpellChecker::isAsynchronousEnabled() const
+{
+    return m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled();
+}
+
+bool SpellChecker::canCheckAsynchronously(Range* range) const
+{
+    return client() && isCheckable(range) && isAsynchronousEnabled();
+}
+
+bool SpellChecker::isCheckable(Range* range) const
+{
+    if (!range || !range->firstNode() || !range->firstNode()->renderer())
+        return false;
+    const Node* node = range->startContainer();
+    if (node && node->isElementNode() && !toElement(node)->isSpellCheckingEnabled())
+        return false;
+    return true;
+}
+
+void SpellChecker::requestCheckingFor(PassRefPtr<SpellCheckRequest> request)
+{
+    if (!request || !canCheckAsynchronously(request->paragraphRange().get()))
+        return;
+
+    ASSERT(request->data().sequence() == unrequestedTextCheckingSequence);
+    int sequence = ++m_lastRequestSequence;
+    if (sequence == unrequestedTextCheckingSequence)
+        sequence = ++m_lastRequestSequence;
+
+    request->setCheckerAndSequence(this, sequence);
+
+    if (m_timerToProcessQueuedRequest.isActive() || m_processingRequest) {
+        enqueueRequest(request);
+        return;
+    }
+
+    invokeRequest(request);
+}
+
+void SpellChecker::cancelCheck()
+{
+    if (m_processingRequest)
+        m_processingRequest->didCancel();
+}
+
+void SpellChecker::invokeRequest(PassRefPtr<SpellCheckRequest> request)
+{
+    ASSERT(!m_processingRequest);
+    if (!client())
+        return;
+    m_processingRequest = request;
+    client()->requestCheckingOfString(m_processingRequest);
+}
+
+void SpellChecker::enqueueRequest(PassRefPtr<SpellCheckRequest> request)
+{
+    ASSERT(request);
+
+    for (RequestQueue::iterator it = m_requestQueue.begin(); it != m_requestQueue.end(); ++it) {
+        if (request->rootEditableElement() != (*it)->rootEditableElement())
+            continue;
+
+        *it = request;
+        return;
+    }
+
+    m_requestQueue.append(request);
+}
+
+void SpellChecker::didCheck(int sequence, const Vector<TextCheckingResult>& results)
+{
+    ASSERT(m_processingRequest);
+    ASSERT(m_processingRequest->data().sequence() == sequence);
+    if (m_processingRequest->data().sequence() != sequence) {
+        m_requestQueue.clear();
+        return;
+    }
+
+    m_frame->editor()->markAndReplaceFor(m_processingRequest, results);
+
+    if (m_lastProcessedSequence < sequence)
+        m_lastProcessedSequence = sequence;
+
+    m_processingRequest.clear();
+    if (!m_requestQueue.isEmpty())
+        m_timerToProcessQueuedRequest.startOneShot(0);
+}
+
+void SpellChecker::didCheckSucceed(int sequence, const Vector<TextCheckingResult>& results)
+{
+    TextCheckingRequestData requestData = m_processingRequest->data();
+    if (requestData.sequence() == sequence) {
+        unsigned markers = 0;
+        if (requestData.mask() & TextCheckingTypeSpelling)
+            markers |= DocumentMarker::Spelling;
+        if (requestData.mask() & TextCheckingTypeGrammar)
+            markers |= DocumentMarker::Grammar;
+        if (markers)
+            m_frame->document()->markers()->removeMarkers(m_processingRequest->checkingRange().get(), markers);
+    }
+    didCheck(sequence, results);
+}
+
+void SpellChecker::didCheckCancel(int sequence)
+{
+    Vector<TextCheckingResult> results;
+    didCheck(sequence, results);
+}
+
+} // namespace WebCore
diff --git a/Source/core/editing/SpellCheckRequester.h b/Source/core/editing/SpellCheckRequester.h
new file mode 100644
index 0000000..0165f32
--- /dev/null
+++ b/Source/core/editing/SpellCheckRequester.h
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SpellCheckRequester_h
+#define SpellCheckRequester_h
+
+#include "core/dom/Element.h"
+#include "core/dom/Range.h"
+#include "core/platform/Timer.h"
+#include "core/platform/text/TextChecking.h"
+#include "wtf/Deque.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class Frame;
+class Node;
+class TextCheckerClient;
+class SpellChecker;
+
+class SpellCheckRequest : public TextCheckingRequest {
+public:
+    static PassRefPtr<SpellCheckRequest> create(TextCheckingTypeMask, TextCheckingProcessType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange);
+    virtual ~SpellCheckRequest();
+
+    PassRefPtr<Range> checkingRange() const { return m_checkingRange; }
+    PassRefPtr<Range> paragraphRange() const { return m_paragraphRange; }
+    PassRefPtr<Element> rootEditableElement() const { return m_rootEditableElement; }
+
+    void setCheckerAndSequence(SpellChecker*, int sequence);
+    void requesterDestroyed();
+    bool isStarted() const { return m_checker; }
+
+    virtual const TextCheckingRequestData& data() const OVERRIDE;
+    virtual void didSucceed(const Vector<TextCheckingResult>&) OVERRIDE;
+    virtual void didCancel() OVERRIDE;
+
+private:
+    SpellCheckRequest(PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange, const String&, TextCheckingTypeMask, TextCheckingProcessType, const Vector<uint32_t>& documentMarkersInRange, const Vector<unsigned>& documentMarkerOffsets);
+
+    SpellChecker* m_checker;
+    RefPtr<Range> m_checkingRange;
+    RefPtr<Range> m_paragraphRange;
+    RefPtr<Element> m_rootEditableElement;
+    TextCheckingRequestData m_requestData;
+};
+
+class SpellChecker {
+    WTF_MAKE_NONCOPYABLE(SpellChecker); WTF_MAKE_FAST_ALLOCATED;
+public:
+    friend class SpellCheckRequest;
+
+    explicit SpellChecker(Frame*);
+    ~SpellChecker();
+
+    bool isAsynchronousEnabled() const;
+    bool isCheckable(Range*) const;
+
+    void requestCheckingFor(PassRefPtr<SpellCheckRequest>);
+    void cancelCheck();
+
+    int lastRequestSequence() const
+    {
+        return m_lastRequestSequence;
+    }
+
+    int lastProcessedSequence() const
+    {
+        return m_lastProcessedSequence;
+    }
+
+private:
+    typedef Deque<RefPtr<SpellCheckRequest> > RequestQueue;
+
+    bool canCheckAsynchronously(Range*) const;
+    TextCheckerClient* client() const;
+    void timerFiredToProcessQueuedRequest(Timer<SpellChecker>*);
+    void invokeRequest(PassRefPtr<SpellCheckRequest>);
+    void enqueueRequest(PassRefPtr<SpellCheckRequest>);
+    void didCheckSucceed(int sequence, const Vector<TextCheckingResult>&);
+    void didCheckCancel(int sequence);
+    void didCheck(int sequence, const Vector<TextCheckingResult>&);
+
+    Frame* m_frame;
+    int m_lastRequestSequence;
+    int m_lastProcessedSequence;
+
+    Timer<SpellChecker> m_timerToProcessQueuedRequest;
+
+    RefPtr<SpellCheckRequest> m_processingRequest;
+    RequestQueue m_requestQueue;
+};
+
+} // namespace WebCore
+
+#endif // SpellCheckRequester_h
diff --git a/Source/core/editing/TextCheckingHelper.cpp b/Source/core/editing/TextCheckingHelper.cpp
index 3a35783..88d171b 100644
--- a/Source/core/editing/TextCheckingHelper.cpp
+++ b/Source/core/editing/TextCheckingHelper.cpp
@@ -410,7 +410,7 @@
     return firstFoundItem;
 }
 
-int TextCheckingHelper::findFirstGrammarDetail(const Vector<GrammarDetail>& grammarDetails, int badGrammarPhraseLocation, int /*badGrammarPhraseLength*/, int startOffset, int endOffset, bool markAll)
+int TextCheckingHelper::findFirstGrammarDetail(const Vector<GrammarDetail>& grammarDetails, int badGrammarPhraseLocation, int startOffset, int endOffset, bool markAll) const
 {
     // Found some bad grammar. Find the earliest detail range that starts in our search range (if any).
     // Optionally add a DocumentMarker for each detail in the range.
@@ -479,7 +479,7 @@
 
 
         // Found some bad grammar. Find the earliest detail range that starts in our search range (if any).
-        int badGrammarIndex = findFirstGrammarDetail(grammarDetails, badGrammarPhraseLocation, badGrammarPhraseLength, paragraph.checkingStart(), paragraph.checkingEnd(), markAll);
+        int badGrammarIndex = findFirstGrammarDetail(grammarDetails, badGrammarPhraseLocation, paragraph.checkingStart(), paragraph.checkingEnd(), markAll);
         if (badGrammarIndex >= 0) {
             ASSERT(static_cast<unsigned>(badGrammarIndex) < grammarDetails.size());
             outGrammarDetail = grammarDetails[badGrammarIndex];
diff --git a/Source/core/editing/TextCheckingHelper.h b/Source/core/editing/TextCheckingHelper.h
index c18021c..853e089 100644
--- a/Source/core/editing/TextCheckingHelper.h
+++ b/Source/core/editing/TextCheckingHelper.h
@@ -83,7 +83,6 @@
     String findFirstMisspelling(int& firstMisspellingOffset, bool markAll, RefPtr<Range>& firstMisspellingRange);
     String findFirstMisspellingOrBadGrammar(bool checkGrammar, bool& outIsSpelling, int& outFirstFoundOffset, GrammarDetail& outGrammarDetail);
     String findFirstBadGrammar(GrammarDetail& outGrammarDetail, int& outGrammarPhraseOffset, bool markAll);
-    int findFirstGrammarDetail(const Vector<GrammarDetail>& grammarDetails, int badGrammarPhraseLocation, int badGrammarPhraseLength, int startOffset, int endOffset, bool markAll);
     void markAllMisspellings(RefPtr<Range>& firstMisspellingRange);
     void markAllBadGrammar();
 
@@ -91,6 +90,7 @@
     EditorClient* m_client;
     RefPtr<Range> m_range;
 
+    int findFirstGrammarDetail(const Vector<GrammarDetail>& grammarDetails, int badGrammarPhraseLocation, int startOffset, int endOffset, bool markAll) const;
     bool unifiedTextCheckerEnabled() const;
 };
 
diff --git a/Source/core/editing/TextIterator.cpp b/Source/core/editing/TextIterator.cpp
index d80ee9f..837b488 100644
--- a/Source/core/editing/TextIterator.cpp
+++ b/Source/core/editing/TextIterator.cpp
@@ -48,6 +48,7 @@
 #include "core/rendering/RenderTextControl.h"
 #include "core/rendering/RenderTextFragment.h"
 #include "wtf/text/CString.h"
+#include "wtf/text/StringBuilder.h"
 #include "wtf/unicode/CharacterNames.h"
 #include <unicode/usearch.h>
 
@@ -1640,7 +1641,7 @@
     // but it doesn't matter exactly what it is, since we don't perform any searches
     // without setting both the pattern and the text.
     UErrorCode status = U_ZERO_ERROR;
-    String searchCollatorName = currentSearchLocaleID() + String(ASCIILiteral("@collation=search"));
+    String searchCollatorName = currentSearchLocaleID() + String("@collation=search");
     UStringSearch* searcher = usearch_open(&newlineCharacter, 1, &newlineCharacter, 1, searchCollatorName.utf8().data(), 0, &status);
     ASSERT(status == U_ZERO_ERROR || status == U_USING_FALLBACK_WARNING || status == U_USING_DEFAULT_WARNING);
     return searcher;
diff --git a/Source/core/editing/VisibleUnits.cpp b/Source/core/editing/VisibleUnits.cpp
index 9e803fc..7ad6c88 100644
--- a/Source/core/editing/VisibleUnits.cpp
+++ b/Source/core/editing/VisibleUnits.cpp
@@ -27,6 +27,7 @@
 #include "core/editing/VisibleUnits.h"
 
 #include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Document.h"
@@ -1109,11 +1110,7 @@
 
     Node* n = startNode;
     while (n) {
-#if ENABLE(USERSELECT_ALL)
         if (boundaryCrossingRule == CannotCrossEditingBoundary && !Position::nodeIsUserSelectAll(n) && n->rendererIsEditable() != startNode->rendererIsEditable())
-#else
-        if (boundaryCrossingRule == CannotCrossEditingBoundary && n->rendererIsEditable() != startNode->rendererIsEditable())
-#endif
             break;
         if (boundaryCrossingRule == CanSkipOverEditingBoundary) {
             while (n && n->rendererIsEditable() != startNode->rendererIsEditable())
@@ -1189,11 +1186,7 @@
 
     Node* n = startNode;
     while (n) {
-#if ENABLE(USERSELECT_ALL)
         if (boundaryCrossingRule == CannotCrossEditingBoundary && !Position::nodeIsUserSelectAll(n) && n->rendererIsEditable() != startNode->rendererIsEditable())
-#else
-        if (boundaryCrossingRule == CannotCrossEditingBoundary && n->rendererIsEditable() != startNode->rendererIsEditable())
-#endif
             break;
         if (boundaryCrossingRule == CanSkipOverEditingBoundary) {
             while (n && n->rendererIsEditable() != startNode->rendererIsEditable())
diff --git a/Source/core/editing/htmlediting.cpp b/Source/core/editing/htmlediting.cpp
index b4b9459..72bf50d 100644
--- a/Source/core/editing/htmlediting.cpp
+++ b/Source/core/editing/htmlediting.cpp
@@ -101,6 +101,11 @@
     return result ? result : bias;
 }
 
+int comparePositions(const PositionWithAffinity& a, const PositionWithAffinity& b)
+{
+    return comparePositions(a.position(), b.position());
+}
+
 int comparePositions(const VisiblePosition& a, const VisiblePosition& b)
 {
     return comparePositions(a.deepEquivalent(), b.deepEquivalent());
diff --git a/Source/core/editing/htmlediting.h b/Source/core/editing/htmlediting.h
index 3500e03..e8bd156 100644
--- a/Source/core/editing/htmlediting.h
+++ b/Source/core/editing/htmlediting.h
@@ -148,6 +148,7 @@
 // comparision functions on Position
 
 int comparePositions(const Position&, const Position&);
+int comparePositions(const PositionWithAffinity&, const PositionWithAffinity&);
 
 // boolean functions on Position
 
diff --git a/Source/core/editing/markup.cpp b/Source/core/editing/markup.cpp
index 383cb1d..a716b90 100644
--- a/Source/core/editing/markup.cpp
+++ b/Source/core/editing/markup.cpp
@@ -193,8 +193,8 @@
 
 const String& StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock)
 {
-    DEFINE_STATIC_LOCAL(const String, divClose, (ASCIILiteral("</div>")));
-    DEFINE_STATIC_LOCAL(const String, styleSpanClose, (ASCIILiteral("</span>")));
+    DEFINE_STATIC_LOCAL(const String, divClose, ("</div>"));
+    DEFINE_STATIC_LOCAL(const String, styleSpanClose, ("</span>"));
     return isBlock ? divClose : styleSpanClose;
 }
 
@@ -463,7 +463,7 @@
         return true;
     if (!value->isPrimitiveValue())
         return false;
-    return static_cast<CSSPrimitiveValue*>(value.get())->getValueID() == CSSValueNone;
+    return toCSSPrimitiveValue(value.get())->getValueID() == CSSValueNone;
 }
 
 static bool needInterchangeNewlineAfter(const VisiblePosition& v)
@@ -547,7 +547,7 @@
     ASSERT(document);
     ASSERT(range);
     ASSERT(updatedRange);
-    DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, (ASCIILiteral("<br class=\"" AppleInterchangeNewline "\">")));
+    DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">"));
 
     bool collapsed = updatedRange->collapsed(ASSERT_NO_EXCEPTION);
     if (collapsed)
diff --git a/Source/core/fileapi/FileReader.idl b/Source/core/fileapi/FileReader.idl
index 2727d12..d43e34e 100644
--- a/Source/core/fileapi/FileReader.idl
+++ b/Source/core/fileapi/FileReader.idl
@@ -54,10 +54,10 @@
 
     readonly attribute FileError error;
 
-    attribute EventListener onloadstart;
-    attribute EventListener onprogress;
-    attribute EventListener onload;
-    attribute EventListener onabort;
-    attribute EventListener onerror;
-    attribute EventListener onloadend;
+    attribute EventHandler onloadstart;
+    attribute EventHandler onprogress;
+    attribute EventHandler onload;
+    attribute EventHandler onabort;
+    attribute EventHandler onerror;
+    attribute EventHandler onloadend;
 };
diff --git a/Source/core/html/BaseCheckableInputType.cpp b/Source/core/html/BaseCheckableInputType.cpp
index 28c069b..6867bd2 100644
--- a/Source/core/html/BaseCheckableInputType.cpp
+++ b/Source/core/html/BaseCheckableInputType.cpp
@@ -44,7 +44,7 @@
 
 FormControlState BaseCheckableInputType::saveFormControlState() const
 {
-    return FormControlState(element()->checked() ? ASCIILiteral("on") : ASCIILiteral("off"));
+    return FormControlState(element()->checked() ? "on" : "off");
 }
 
 void BaseCheckableInputType::restoreFormControlState(const FormControlState& state)
@@ -93,7 +93,7 @@
 
 String BaseCheckableInputType::fallbackValue() const
 {
-    return ASCIILiteral("on");
+    return "on";
 }
 
 bool BaseCheckableInputType::storesValueSeparateFromAttribute()
diff --git a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
index 283fbd6..ae80ddb 100644
--- a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
@@ -62,7 +62,7 @@
     DEFINE_STATIC_LOCAL(AtomicString, valueContainerPseudo, ("-webkit-date-and-time-value", AtomicString::ConstructFromLiteral));
 
     RefPtr<HTMLDivElement> valueContainer = HTMLDivElement::create(element()->document());
-    valueContainer->setPseudo(valueContainerPseudo);
+    valueContainer->setPart(valueContainerPseudo);
     element()->userAgentShadowRoot()->appendChild(valueContainer.get());
     updateAppearance();
 }
@@ -75,7 +75,7 @@
     String displayValue = visibleValue();
     if (displayValue.isEmpty()) {
         // Need to put something to keep text baseline.
-        displayValue = ASCIILiteral(" ");
+        displayValue = " ";
     }
     toHTMLElement(node)->setInnerText(displayValue, ASSERT_NO_EXCEPTION);
 }
diff --git a/Source/core/html/BaseDateAndTimeInputType.cpp b/Source/core/html/BaseDateAndTimeInputType.cpp
index c86d076..71207df 100644
--- a/Source/core/html/BaseDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseDateAndTimeInputType.cpp
@@ -156,7 +156,7 @@
 
 String BaseDateAndTimeInputType::sanitizeValue(const String& proposedValue) const
 {
-    return typeMismatchFor(proposedValue) ? String() : proposedValue;
+    return typeMismatchFor(proposedValue) ? emptyString() : proposedValue;
 }
 
 bool BaseDateAndTimeInputType::supportsReadOnly() const
diff --git a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
index ac5c46f..8ea2d94 100644
--- a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
@@ -130,22 +130,22 @@
 
 DateTimeEditElement* BaseMultipleFieldsDateAndTimeInputType::dateTimeEditElement() const
 {
-    return toDateTimeEditElement(elementById(ShadowElementNames::dateTimeEdit()));
+    return toDateTimeEditElement(element()->uaShadowElementById(ShadowElementNames::dateTimeEdit()));
 }
 
 SpinButtonElement* BaseMultipleFieldsDateAndTimeInputType::spinButtonElement() const
 {
-    return toSpinButtonElement(elementById(ShadowElementNames::spinButton()));
+    return toSpinButtonElement(element()->uaShadowElementById(ShadowElementNames::spinButton()));
 }
 
 ClearButtonElement* BaseMultipleFieldsDateAndTimeInputType::clearButtonElement() const
 {
-    return toClearButtonElement(elementById(ShadowElementNames::clearButton()));
+    return toClearButtonElement(element()->uaShadowElementById(ShadowElementNames::clearButton()));
 }
 
 PickerIndicatorElement* BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorElement() const
 {
-    return toPickerIndicatorElement(elementById(ShadowElementNames::pickerIndicator()));
+    return toPickerIndicatorElement(element()->uaShadowElementById(ShadowElementNames::pickerIndicator()));
 }
 
 inline bool BaseMultipleFieldsDateAndTimeInputType::containsFocusedShadowElement() const
@@ -379,7 +379,7 @@
         return;
     if (direction == FocusDirectionBackward) {
         if (element()->document()->page())
-            element()->document()->page()->focusController()->advanceFocus(direction);
+            element()->document()->page()->focusController().advanceFocus(direction);
     } else if (direction == FocusDirectionNone || direction == FocusDirectionMouse) {
         edit->focusByOwner(oldFocusedElement);
     } else
diff --git a/Source/core/html/ColorInputType.cpp b/Source/core/html/ColorInputType.cpp
index 6c2c716..46e741a 100644
--- a/Source/core/html/ColorInputType.cpp
+++ b/Source/core/html/ColorInputType.cpp
@@ -120,9 +120,9 @@
 
     Document* document = element()->document();
     RefPtr<HTMLDivElement> wrapperElement = HTMLDivElement::create(document);
-    wrapperElement->setPseudo(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
+    wrapperElement->setPart(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
     RefPtr<HTMLDivElement> colorSwatch = HTMLDivElement::create(document);
-    colorSwatch->setPseudo(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
+    colorSwatch->setPart(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
     wrapperElement->appendChild(colorSwatch.release(), ASSERT_NO_EXCEPTION);
     element()->userAgentShadowRoot()->appendChild(wrapperElement.release(), ASSERT_NO_EXCEPTION);
 
diff --git a/Source/core/html/DOMTokenList.idl b/Source/core/html/DOMTokenList.idl
index c885018..3f16677 100644
--- a/Source/core/html/DOMTokenList.idl
+++ b/Source/core/html/DOMTokenList.idl
@@ -28,9 +28,9 @@
     readonly attribute unsigned long length;
     [TreatReturnedNullStringAs=Null] getter DOMString item(unsigned long index);
     [RaisesException] boolean contains(DOMString token);
-    [RaisesException, DeliverCustomElementCallbacks] void add(DOMString... tokens);
-    [RaisesException, DeliverCustomElementCallbacks] void remove(DOMString... tokens);
-    [RaisesException, DeliverCustomElementCallbacks] boolean toggle(DOMString token, optional boolean force);
+    [RaisesException, CustomElementCallbacks=Enable] void add(DOMString... tokens);
+    [RaisesException, CustomElementCallbacks=Enable] void remove(DOMString... tokens);
+    [RaisesException, CustomElementCallbacks=Enable] boolean toggle(DOMString token, optional boolean force);
     [NotEnumerable] DOMString toString();
 };
 
diff --git a/Source/core/html/DateInputType.cpp b/Source/core/html/DateInputType.cpp
index ec2f6a0..b18edd8 100644
--- a/Source/core/html/DateInputType.cpp
+++ b/Source/core/html/DateInputType.cpp
@@ -114,7 +114,7 @@
 void DateInputType::setupLayoutParameters(DateTimeEditElement::LayoutParameters& layoutParameters, const DateComponents& date) const
 {
     layoutParameters.dateTimeFormat = layoutParameters.locale.dateFormat();
-    layoutParameters.fallbackDateTimeFormat = ASCIILiteral("yyyy-MM-dd");
+    layoutParameters.fallbackDateTimeFormat = "yyyy-MM-dd";
     if (!parseToDateComponents(element()->fastGetAttribute(minAttr), &layoutParameters.minimum))
         layoutParameters.minimum = DateComponents();
     if (!parseToDateComponents(element()->fastGetAttribute(maxAttr), &layoutParameters.maximum))
diff --git a/Source/core/html/FileInputType.cpp b/Source/core/html/FileInputType.cpp
index 1623ac5..8db9fad 100644
--- a/Source/core/html/FileInputType.cpp
+++ b/Source/core/html/FileInputType.cpp
@@ -259,7 +259,7 @@
     RefPtr<HTMLInputElement> button = HTMLInputElement::create(inputTag, element()->document(), 0, false);
     button->setType(InputTypeNames::button());
     button->setAttribute(valueAttr, element()->multiple() ? fileButtonChooseMultipleFilesLabel() : fileButtonChooseFileLabel());
-    button->setPseudo(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
+    button->setPart(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
     element()->userAgentShadowRoot()->appendChild(button.release(), IGNORE_EXCEPTION);
 }
 
diff --git a/Source/core/html/FormController.cpp b/Source/core/html/FormController.cpp
index 5b2ff3c..942ab0e 100644
--- a/Source/core/html/FormController.cpp
+++ b/Source/core/html/FormController.cpp
@@ -387,7 +387,7 @@
     // In the legacy version of serialized state, the first item was a name
     // attribute value of a form control. The following string literal should
     // contain some characters which are rarely used for name attribute values.
-    DEFINE_STATIC_LOCAL(String, signature, (ASCIILiteral("\n\r?% WebKit serialized form state version 8 \n\r=&")));
+    DEFINE_STATIC_LOCAL(String, signature, ("\n\r?% WebKit serialized form state version 8 \n\r=&"));
     return signature;
 }
 
diff --git a/Source/core/html/HTMLBodyElement.idl b/Source/core/html/HTMLBodyElement.idl
index f65097a..dfbd907 100644
--- a/Source/core/html/HTMLBodyElement.idl
+++ b/Source/core/html/HTMLBodyElement.idl
@@ -27,28 +27,28 @@
     [Reflect] attribute DOMString vLink;
 
     // Event handler attributes
-    [NotEnumerable] attribute EventListener onbeforeunload;
-    [NotEnumerable] attribute EventListener onhashchange;
-    [NotEnumerable] attribute EventListener onmessage;
-    [NotEnumerable] attribute EventListener onoffline;
-    [NotEnumerable] attribute EventListener ononline;
-    [NotEnumerable] attribute EventListener onpopstate;
-    [NotEnumerable] attribute EventListener onresize;
-    [NotEnumerable] attribute EventListener onstorage;
-    [NotEnumerable] attribute EventListener onunload;
+    [NotEnumerable] attribute EventHandler onbeforeunload;
+    [NotEnumerable] attribute EventHandler onhashchange;
+    [NotEnumerable] attribute EventHandler onmessage;
+    [NotEnumerable] attribute EventHandler onoffline;
+    [NotEnumerable] attribute EventHandler ononline;
+    [NotEnumerable] attribute EventHandler onpopstate;
+    [NotEnumerable] attribute EventHandler onresize;
+    [NotEnumerable] attribute EventHandler onstorage;
+    [NotEnumerable] attribute EventHandler onunload;
 
-    [Conditional=ORIENTATION_EVENTS, NotEnumerable] attribute EventListener onorientationchange;
+    [Conditional=ORIENTATION_EVENTS, NotEnumerable] attribute EventHandler onorientationchange;
 
     // Overrides of Element attributes (with different implementation in bindings).
-    [NotEnumerable] attribute EventListener onblur;
-    [NotEnumerable] attribute EventListener onerror;
-    [NotEnumerable] attribute EventListener onfocus;
-    [NotEnumerable] attribute EventListener onload;
+    [NotEnumerable] attribute EventHandler onblur;
+    [NotEnumerable] attribute EventHandler onerror;
+    [NotEnumerable] attribute EventHandler onfocus;
+    [NotEnumerable] attribute EventHandler onload;
 
     // Not implemented yet.
-    // attribute [NotEnumerable] EventListener onafterprint;
-    // attribute [NotEnumerable] EventListener onbeforeprint;
-    // attribute [NotEnumerable] EventListener onredo;
-    // attribute [NotEnumerable] EventListener onundo;
+    // attribute [NotEnumerable] EventHandler onafterprint;
+    // attribute [NotEnumerable] EventHandler onbeforeprint;
+    // attribute [NotEnumerable] EventHandler onredo;
+    // attribute [NotEnumerable] EventHandler onundo;
 };
 
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index 81a2a39..9a68a4d 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -120,10 +120,10 @@
     return HTMLElement::createRenderer(style);
 }
 
-void HTMLCanvasElement::attach(const AttachContext& context)
+Node::InsertionNotificationRequest HTMLCanvasElement::insertedInto(ContainerNode* node)
 {
     setIsInCanvasSubtree(true);
-    HTMLElement::attach(context);
+    return HTMLElement::insertedInto(node);
 }
 
 void HTMLCanvasElement::addObserver(CanvasObserver* observer)
diff --git a/Source/core/html/HTMLCanvasElement.h b/Source/core/html/HTMLCanvasElement.h
index 2aed48b..1de3401 100644
--- a/Source/core/html/HTMLCanvasElement.h
+++ b/Source/core/html/HTMLCanvasElement.h
@@ -133,12 +133,13 @@
 
     float deviceScaleFactor() const { return m_deviceScaleFactor; }
 
+    InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
+
 private:
     HTMLCanvasElement(const QualifiedName&, Document*);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
 
     void reset();
diff --git a/Source/core/html/HTMLDocument.cpp b/Source/core/html/HTMLDocument.cpp
index 33f5417..704547f 100644
--- a/Source/core/html/HTMLDocument.cpp
+++ b/Source/core/html/HTMLDocument.cpp
@@ -121,9 +121,9 @@
     Page* page = this->page();
     if (!page)
         return false;
-    if (!page->focusController()->isActive())
+    if (!page->focusController().isActive() || !page->focusController().isFocused())
         return false;
-    if (Frame* focusedFrame = page->focusController()->focusedFrame()) {
+    if (Frame* focusedFrame = page->focusController().focusedFrame()) {
         if (focusedFrame->tree()->isDescendantOf(frame()))
             return true;
     }
@@ -216,6 +216,11 @@
     }
 }
 
+PassRefPtr<Document> HTMLDocument::cloneDocumentWithoutChildren()
+{
+    return create();
+}
+
 // --------------------------------------------------------------------------
 // not part of the DOM
 // --------------------------------------------------------------------------
diff --git a/Source/core/html/HTMLDocument.h b/Source/core/html/HTMLDocument.h
index 4d6332e..993fbc0 100644
--- a/Source/core/html/HTMLDocument.h
+++ b/Source/core/html/HTMLDocument.h
@@ -76,6 +76,8 @@
 
     static bool isCaseSensitiveAttribute(const QualifiedName&);
 
+    virtual PassRefPtr<Document> cloneDocumentWithoutChildren() OVERRIDE FINAL;
+
 protected:
     HTMLDocument(const DocumentInit&, DocumentClassFlags extendedDocumentClasses = DefaultDocumentClass);
 
diff --git a/Source/core/html/HTMLDocument.idl b/Source/core/html/HTMLDocument.idl
index 574f21b..e44baee 100644
--- a/Source/core/html/HTMLDocument.idl
+++ b/Source/core/html/HTMLDocument.idl
@@ -21,10 +21,10 @@
 [
     CustomToV8
 ] interface HTMLDocument : Document {
-    [Custom] void open();
+    [Custom, CustomElementCallbacks=Enable] void open();
     void close();
-    [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void write([Default=Undefined] optional DOMString text);
-    [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void writeln([Default=Undefined] optional DOMString text);
+    [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, CustomElementCallbacks=Enable] void write([Default=Undefined] optional DOMString text);
+    [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, CustomElementCallbacks=Enable] void writeln([Default=Undefined] optional DOMString text);
 
     readonly attribute HTMLCollection embeds;
     readonly attribute HTMLCollection plugins;
@@ -39,18 +39,18 @@
     [DeprecateAs=CaptureEvents] void captureEvents();
     [DeprecateAs=ReleaseEvents] void releaseEvents();
 
-    [TreatNullAs=NullString] attribute DOMString dir;
-    [TreatNullAs=NullString] attribute DOMString designMode;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString dir;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString designMode;
     readonly attribute DOMString compatMode;
 
     readonly attribute Element activeElement;
     boolean hasFocus();
 
     // Deprecated attributes
-             [TreatNullAs=NullString] attribute DOMString bgColor;
-             [TreatNullAs=NullString] attribute DOMString fgColor;
-             [TreatNullAs=NullString] attribute DOMString alinkColor;
-             [TreatNullAs=NullString] attribute DOMString linkColor;
-             [TreatNullAs=NullString] attribute DOMString vlinkColor;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString bgColor;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString fgColor;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString alinkColor;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString linkColor;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString vlinkColor;
 };
 
diff --git a/Source/core/html/HTMLElement.idl b/Source/core/html/HTMLElement.idl
index 7f97db6..d728075 100644
--- a/Source/core/html/HTMLElement.idl
+++ b/Source/core/html/HTMLElement.idl
@@ -26,28 +26,28 @@
              attribute boolean             translate;
              [Reflect] attribute DOMString dir;
 
-             attribute long              tabIndex;
-             attribute boolean           draggable;
+             [CustomElementCallbacks=Enable] attribute long              tabIndex;
+             [CustomElementCallbacks=Enable] attribute boolean           draggable;
              [Reflect] attribute DOMString webkitdropzone;
              [Reflect] attribute boolean hidden;
              [Reflect] attribute DOMString accessKey;
 
     // Extensions
-             [TreatNullAs=NullString, DeliverCustomElementCallbacks, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds, SetterRaisesException] attribute DOMString innerHTML;
-             [TreatNullAs=NullString, SetterRaisesException] attribute DOMString innerText;
-             [TreatNullAs=NullString, DeliverCustomElementCallbacks, SetterRaisesException] attribute DOMString outerHTML;
-             [TreatNullAs=NullString, SetterRaisesException] attribute DOMString outerText;
+             [TreatNullAs=NullString, CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds, SetterRaisesException] attribute DOMString innerHTML;
+             [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString innerText;
+             [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString outerHTML;
+             [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString outerText;
 
-    [RaisesException] Element insertAdjacentElement([Default=Undefined] optional DOMString where,
+    [RaisesException, CustomElementCallbacks=Enable] Element insertAdjacentElement([Default=Undefined] optional DOMString where,
                                   [Default=Undefined] optional Element element);
-    [DeliverCustomElementCallbacks, RaisesException] void insertAdjacentHTML([Default=Undefined] optional DOMString where,
+    [CustomElementCallbacks=Enable, RaisesException] void insertAdjacentHTML([Default=Undefined] optional DOMString where,
                             [Default=Undefined] optional DOMString html);
     [RaisesException] void insertAdjacentText([Default=Undefined] optional DOMString where,
                             [Default=Undefined] optional DOMString text);
 
     [EnabledAtRuntime=imeAPI] readonly attribute InputMethodContext inputMethodContext;
 
-             [TreatNullAs=NullString, SetterRaisesException] attribute DOMString contentEditable;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString contentEditable;
     readonly attribute boolean isContentEditable;
 
              attribute boolean spellcheck;
diff --git a/Source/core/html/HTMLFormElement.idl b/Source/core/html/HTMLFormElement.idl
index cd2b3c7..11c8bf5 100644
--- a/Source/core/html/HTMLFormElement.idl
+++ b/Source/core/html/HTMLFormElement.idl
@@ -22,9 +22,9 @@
     [Reflect=accept_charset] attribute DOMString acceptCharset;
     [Reflect, URL] attribute DOMString action;
     [Reflect] attribute DOMString autocomplete;
-    [TreatNullAs=NullString] attribute DOMString enctype;
-    [TreatNullAs=NullString] attribute DOMString encoding;
-    [TreatNullAs=NullString] attribute DOMString method;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString enctype;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString encoding;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString method;
     [Reflect] attribute DOMString name;
     [Reflect] attribute boolean noValidate;
     [Reflect] attribute DOMString target;
@@ -35,10 +35,10 @@
     [ImplementedAs=anonymousNamedGetter, OverrideBuiltins, NotEnumerable] getter (NodeList or Node)(DOMString name);
 
     [ImplementedAs=submitFromJavaScript] void submit();
-    void reset();
+    [CustomElementCallbacks=Enable] void reset();
     boolean checkValidity();
 
     [EnabledAtRuntime=requestAutocomplete] void requestAutocomplete();
-    [EnabledAtRuntime=requestAutocomplete,NotEnumerable] attribute EventListener onautocomplete;
-    [EnabledAtRuntime=requestAutocomplete,NotEnumerable] attribute EventListener onautocompleteerror;
+    [EnabledAtRuntime=requestAutocomplete,NotEnumerable] attribute EventHandler onautocomplete;
+    [EnabledAtRuntime=requestAutocomplete,NotEnumerable] attribute EventHandler onautocompleteerror;
 };
diff --git a/Source/core/html/HTMLFrameElementBase.cpp b/Source/core/html/HTMLFrameElementBase.cpp
index 6f1a431..d04a479 100644
--- a/Source/core/html/HTMLFrameElementBase.cpp
+++ b/Source/core/html/HTMLFrameElementBase.cpp
@@ -208,9 +208,9 @@
     HTMLFrameOwnerElement::setFocus(received);
     if (Page* page = document()->page()) {
         if (received)
-            page->focusController()->setFocusedFrame(contentFrame());
-        else if (page->focusController()->focusedFrame() == contentFrame()) // Focus may have already been given to another frame, don't take it away.
-            page->focusController()->setFocusedFrame(0);
+            page->focusController().setFocusedFrame(contentFrame());
+        else if (page->focusController().focusedFrame() == contentFrame()) // Focus may have already been given to another frame, don't take it away.
+            page->focusController().setFocusedFrame(0);
     }
 }
 
diff --git a/Source/core/html/HTMLFrameOwnerElement.cpp b/Source/core/html/HTMLFrameOwnerElement.cpp
index 8378678..f197d80 100644
--- a/Source/core/html/HTMLFrameOwnerElement.cpp
+++ b/Source/core/html/HTMLFrameOwnerElement.cpp
@@ -140,7 +140,7 @@
     RefPtr<Frame> childFrame = parentFrame->loader()->client()->createFrame(url, frameName, this, referrer, allowScrollingInContentFrame(), marginWidth(), marginHeight());
 
     if (!childFrame)  {
-        parentFrame->loader()->checkCallImplicitClose();
+        parentFrame->loader()->checkCompleted();
         return false;
     }
 
@@ -157,8 +157,6 @@
     if (renderObject && renderObject->isWidget() && view)
         toRenderWidget(renderObject)->setWidget(view);
 
-    parentFrame->loader()->checkCallImplicitClose();
-
     // Some loads are performed synchronously (e.g., about:blank and loads
     // cancelled by returning a null ResourceRequest from requestFromDelegate).
     // In these cases, the synchronous load would have finished
diff --git a/Source/core/html/HTMLFrameSetElement.cpp b/Source/core/html/HTMLFrameSetElement.cpp
index d806c61..43f18e2 100644
--- a/Source/core/html/HTMLFrameSetElement.cpp
+++ b/Source/core/html/HTMLFrameSetElement.cpp
@@ -209,7 +209,7 @@
 void HTMLFrameSetElement::willRecalcStyle(StyleChange)
 {
     if (needsStyleRecalc() && renderer()) {
-        renderer()->setNeedsLayout(true);
+        renderer()->setNeedsLayout();
         clearNeedsStyleRecalc();
     }
 }
diff --git a/Source/core/html/HTMLFrameSetElement.idl b/Source/core/html/HTMLFrameSetElement.idl
index 09c262c..0a35684 100644
--- a/Source/core/html/HTMLFrameSetElement.idl
+++ b/Source/core/html/HTMLFrameSetElement.idl
@@ -24,28 +24,28 @@
     [Reflect] attribute DOMString rows;
 
     // Event handler attributes
-    [NotEnumerable] attribute EventListener onbeforeunload;
-    [NotEnumerable] attribute EventListener onhashchange;
-    [NotEnumerable] attribute EventListener onmessage;
-    [NotEnumerable] attribute EventListener onoffline;
-    [NotEnumerable] attribute EventListener ononline;
-    [NotEnumerable] attribute EventListener onpopstate;
-    [NotEnumerable] attribute EventListener onresize;
-    [NotEnumerable] attribute EventListener onstorage;
-    [NotEnumerable] attribute EventListener onunload;
+    [NotEnumerable] attribute EventHandler onbeforeunload;
+    [NotEnumerable] attribute EventHandler onhashchange;
+    [NotEnumerable] attribute EventHandler onmessage;
+    [NotEnumerable] attribute EventHandler onoffline;
+    [NotEnumerable] attribute EventHandler ononline;
+    [NotEnumerable] attribute EventHandler onpopstate;
+    [NotEnumerable] attribute EventHandler onresize;
+    [NotEnumerable] attribute EventHandler onstorage;
+    [NotEnumerable] attribute EventHandler onunload;
 
-    [Conditional=ORIENTATION_EVENTS, NotEnumerable] attribute EventListener onorientationchange;
+    [Conditional=ORIENTATION_EVENTS, NotEnumerable] attribute EventHandler onorientationchange;
 
     // Overrides of Element attributes (with different implementation in bindings).
-    [NotEnumerable] attribute EventListener onblur;
-    [NotEnumerable] attribute EventListener onerror;
-    [NotEnumerable] attribute EventListener onfocus;
-    [NotEnumerable] attribute EventListener onload;
+    [NotEnumerable] attribute EventHandler onblur;
+    [NotEnumerable] attribute EventHandler onerror;
+    [NotEnumerable] attribute EventHandler onfocus;
+    [NotEnumerable] attribute EventHandler onload;
 
     // Not implemented yet.
-    // attribute [NotEnumerable] EventListener onafterprint;
-    // attribute [NotEnumerable] EventListener onbeforeprint;
-    // attribute [NotEnumerable] EventListener onredo;
-    // attribute [NotEnumerable] EventListener onundo;
+    // attribute [NotEnumerable] EventHandler onafterprint;
+    // attribute [NotEnumerable] EventHandler onbeforeprint;
+    // attribute [NotEnumerable] EventHandler onredo;
+    // attribute [NotEnumerable] EventHandler onundo;
 };
 
diff --git a/Source/core/html/HTMLImageElement.cpp b/Source/core/html/HTMLImageElement.cpp
index 2303be2..571462b 100644
--- a/Source/core/html/HTMLImageElement.cpp
+++ b/Source/core/html/HTMLImageElement.cpp
@@ -30,7 +30,7 @@
 #include "core/dom/EventNames.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/RenderImage.h"
 
 using namespace std;
@@ -171,7 +171,7 @@
         if (!m_imageLoader.image() && !renderImageResource->cachedImage())
             renderImage->setImageSizeForAltText();
         else
-            renderImageResource->setCachedImage(m_imageLoader.image());
+            renderImageResource->setImageResource(m_imageLoader.image());
 
     }
 }
diff --git a/Source/core/html/HTMLImageElement.h b/Source/core/html/HTMLImageElement.h
index 7810d28..590b0ec 100644
--- a/Source/core/html/HTMLImageElement.h
+++ b/Source/core/html/HTMLImageElement.h
@@ -53,8 +53,8 @@
 
     CompositeOperator compositeOperator() const { return m_compositeOperator; }
 
-    CachedImage* cachedImage() const { return m_imageLoader.image(); }
-    void setCachedImage(CachedImage* i) { m_imageLoader.setImage(i); };
+    ImageResource* cachedImage() const { return m_imageLoader.image(); }
+    void setImageResource(ImageResource* i) { m_imageLoader.setImage(i); };
 
     void setLoadManually(bool loadManually) { m_imageLoader.setLoadManually(loadManually); }
 
diff --git a/Source/core/html/HTMLImageLoader.cpp b/Source/core/html/HTMLImageLoader.cpp
index de4ee64..6b966ac 100644
--- a/Source/core/html/HTMLImageLoader.cpp
+++ b/Source/core/html/HTMLImageLoader.cpp
@@ -29,7 +29,7 @@
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 
 namespace WebCore {
 
@@ -61,7 +61,7 @@
 
 void HTMLImageLoader::notifyFinished(Resource*)
 {
-    CachedImage* cachedImage = image();
+    ImageResource* cachedImage = image();
 
     RefPtr<Element> element = this->element();
     ImageLoader::notifyFinished(cachedImage);
diff --git a/Source/core/html/HTMLImport.cpp b/Source/core/html/HTMLImport.cpp
index a6c0886..9b1230d 100644
--- a/Source/core/html/HTMLImport.cpp
+++ b/Source/core/html/HTMLImport.cpp
@@ -31,7 +31,7 @@
 #include "config.h"
 #include "core/html/HTMLImport.h"
 
-#include "core/html/HTMLImportsController.h"
+#include "core/dom/Document.h"
 
 namespace WebCore {
 
@@ -42,7 +42,12 @@
 
 Document* HTMLImport::master()
 {
-    return controller()->document();
+    return root()->document();
+}
+
+HTMLImportsController* HTMLImport::controller()
+{
+    return root()->toController();
 }
 
 void HTMLImport::appendChild(HTMLImport* child)
diff --git a/Source/core/html/HTMLImport.h b/Source/core/html/HTMLImport.h
index ecdfd5f..215dad9 100644
--- a/Source/core/html/HTMLImport.h
+++ b/Source/core/html/HTMLImport.h
@@ -38,6 +38,7 @@
 class Frame;
 class Document;
 class Frame;
+class HTMLImportRoot;
 class HTMLImportsController;
 
 class HTMLImport {
@@ -48,12 +49,13 @@
 
     Frame* frame();
     Document* master();
+    HTMLImportsController* controller();
 
     bool isLoaded() const { return !isBlocked() && !isProcessing(); }
     bool isBlocked() const { return m_blocked; }
     void appendChild(HTMLImport*);
 
-    virtual HTMLImportsController* controller() = 0;
+    virtual HTMLImportRoot* root() = 0;
     virtual HTMLImport* parent() const = 0;
     virtual Document* document() const = 0;
     virtual void wasDetachedFromDocument() = 0;
@@ -81,6 +83,12 @@
     bool m_blocked; // If any of decendants or predecessors is in processing, it is blocked.
 };
 
+class HTMLImportRoot : public HTMLImport {
+public:
+    virtual void importWasDisposed() = 0;
+    virtual HTMLImportsController* toController() = 0;
+};
+
 } // namespace WebCore
 
 #endif // HTMLImport_h
diff --git a/Source/core/html/HTMLImportLoader.cpp b/Source/core/html/HTMLImportLoader.cpp
new file mode 100644
index 0000000..ef2d766
--- /dev/null
+++ b/Source/core/html/HTMLImportLoader.cpp
@@ -0,0 +1,202 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/HTMLImportLoader.h"
+
+#include "core/dom/Document.h"
+#include "core/html/HTMLDocument.h"
+#include "core/html/HTMLImportLoaderClient.h"
+#include "core/loader/DocumentWriter.h"
+#include "core/loader/cache/ResourceFetcher.h"
+#include "core/page/ContentSecurityPolicyResponseHeaders.h"
+
+namespace WebCore {
+
+HTMLImportLoader::HTMLImportLoader(HTMLImport* parent, const KURL& url, const ResourcePtr<RawResource>& resource)
+    : m_parent(parent)
+    , m_state(StateLoading)
+    , m_resource(resource)
+    , m_url(url)
+{
+    m_resource->addClient(this);
+}
+
+HTMLImportLoader::~HTMLImportLoader()
+{
+    // importDestroyed() should be called before the destruction.
+    ASSERT(!m_parent);
+    ASSERT(!m_importedDocument);
+    if (m_resource)
+        m_resource->removeClient(this);
+}
+
+void HTMLImportLoader::responseReceived(Resource*, const ResourceResponse& response)
+{
+    setState(startWritingAndParsing(response));
+}
+
+void HTMLImportLoader::dataReceived(Resource*, const char* data, int length)
+{
+    RefPtr<DocumentWriter> protectingWriter(m_writer);
+    m_writer->addData(data, length);
+}
+
+void HTMLImportLoader::notifyFinished(Resource*)
+{
+    setState(finishWriting());
+}
+
+void HTMLImportLoader::setState(State state)
+{
+    if (m_state == state)
+        return;
+
+    m_state = state;
+
+    if (m_state == StateReady || m_state == StateError || m_state == StateWritten) {
+        if (RefPtr<DocumentWriter> writer = m_writer.release())
+            writer->end();
+    }
+
+    // Since DocumentWriter::end() let setState() reenter, we shouldn't refer to m_state here.
+    if (state == StateReady || state == StateError)
+        didFinish();
+}
+
+void HTMLImportLoader::didFinish()
+{
+    for (size_t i = 0; i < m_clients.size(); ++i)
+        m_clients[i]->didFinish();
+
+    if (m_resource) {
+        m_resource->removeClient(this);
+        m_resource = 0;
+    }
+
+    ASSERT(!document() || !document()->parsing());
+    root()->importWasDisposed();
+}
+
+HTMLImportLoader::State HTMLImportLoader::startWritingAndParsing(const ResourceResponse& response)
+{
+    // Current canAccess() implementation isn't sufficient for catching cross-domain redirects: http://crbug.com/256976
+    if (!m_parent->document()->fetcher()->canAccess(m_resource.get()))
+        return StateError;
+
+    m_importedDocument = HTMLDocument::create(DocumentInit(response.url(), 0, this).withRegistrationContext(root()->document()->registrationContext()));
+    m_importedDocument->initContentSecurityPolicy(ContentSecurityPolicyResponseHeaders(response));
+    m_writer = DocumentWriter::create(m_importedDocument.get(), response.mimeType(), response.textEncodingName());
+
+    return StateLoading;
+}
+
+HTMLImportLoader::State HTMLImportLoader::finishWriting()
+{
+    if (!m_parent)
+        return StateError;
+    // The writer instance indicates that a part of the document can be already loaded.
+    // We don't take such a case as an error because the partially-loaded document has been visible from script at this point.
+    if (m_resource->loadFailedOrCanceled() && !m_writer)
+        return StateError;
+
+    return StateWritten;
+}
+
+HTMLImportLoader::State HTMLImportLoader::finishParsing()
+{
+    if (!m_parent)
+        return StateError;
+    return StateReady;
+}
+
+Document* HTMLImportLoader::importedDocument() const
+{
+    if (m_state == StateError)
+        return 0;
+    return m_importedDocument.get();
+}
+
+void HTMLImportLoader::addClient(HTMLImportLoaderClient* client)
+{
+    ASSERT(notFound == m_clients.find(client));
+    m_clients.append(client);
+    if (isDone())
+        client->didFinish();
+}
+
+void HTMLImportLoader::removeClient(HTMLImportLoaderClient* client)
+{
+    ASSERT(notFound != m_clients.find(client));
+    m_clients.remove(m_clients.find(client));
+}
+
+void HTMLImportLoader::importDestroyed()
+{
+    m_parent = 0;
+    if (RefPtr<Document> document = m_importedDocument.release())
+        document->setImport(0);
+}
+
+HTMLImportRoot* HTMLImportLoader::root()
+{
+    return m_parent ? m_parent->root() : 0;
+}
+
+HTMLImport* HTMLImportLoader::parent() const
+{
+    return m_parent;
+}
+
+Document* HTMLImportLoader::document() const
+{
+    return m_importedDocument.get();
+}
+
+void HTMLImportLoader::wasDetachedFromDocument()
+{
+    // For imported documens this shouldn't be called because Document::m_import is
+    // cleared before Document is destroyed by HTMLImportLoader::importDestroyed().
+    ASSERT_NOT_REACHED();
+}
+
+void HTMLImportLoader::didFinishParsing()
+{
+    setState(finishParsing());
+}
+
+bool HTMLImportLoader::isProcessing() const
+{
+    if (!m_importedDocument)
+        return !isDone();
+    return m_importedDocument->parsing();
+}
+
+} // namespace WebCore
diff --git a/Source/core/html/HTMLImportLoader.h b/Source/core/html/HTMLImportLoader.h
new file mode 100644
index 0000000..4b9b399
--- /dev/null
+++ b/Source/core/html/HTMLImportLoader.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef HTMLImportLoader_h
+#define HTMLImportLoader_h
+
+#include "core/html/HTMLImport.h"
+#include "core/loader/cache/RawResource.h"
+#include "core/loader/cache/ResourcePtr.h"
+#include "weborigin/KURL.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class DocumentWriter;
+class HTMLImportLoaderClient;
+
+class HTMLImportLoader : public RefCounted<HTMLImportLoader>, public HTMLImport, public RawResourceClient {
+public:
+    enum State {
+        StateLoading,
+        StateWritten,
+        StateError,
+        StateReady
+    };
+
+    HTMLImportLoader(HTMLImport*, const KURL&, const ResourcePtr<RawResource>&);
+    virtual ~HTMLImportLoader();
+
+    Document* importedDocument() const;
+    const KURL& url() const { return m_url; }
+
+    void addClient(HTMLImportLoaderClient*);
+    void removeClient(HTMLImportLoaderClient*);
+    void importDestroyed();
+    bool isDone() const { return m_state == StateReady || m_state == StateError; }
+    bool isLoaded() const { return m_state == StateReady; }
+
+    // HTMLImport
+    virtual HTMLImportRoot* root() OVERRIDE;
+    virtual HTMLImport* parent() const OVERRIDE;
+    virtual Document* document() const OVERRIDE;
+    virtual void wasDetachedFromDocument() OVERRIDE;
+    virtual void didFinishParsing() OVERRIDE;
+    virtual bool isProcessing() const OVERRIDE;
+
+private:
+
+    // RawResourceClient
+    virtual void responseReceived(Resource*, const ResourceResponse&) OVERRIDE;
+    virtual void dataReceived(Resource*, const char* data, int length) OVERRIDE;
+    virtual void notifyFinished(Resource*) OVERRIDE;
+
+    State startWritingAndParsing(const ResourceResponse&);
+    State finishWriting();
+    State finishParsing();
+
+    void setState(State);
+    void didFinish();
+
+    HTMLImport* m_parent;
+    Vector<HTMLImportLoaderClient*> m_clients;
+    State m_state;
+    KURL m_url;
+    ResourcePtr<RawResource> m_resource;
+    RefPtr<Document> m_importedDocument;
+    RefPtr<DocumentWriter> m_writer;
+};
+
+} // namespace WebCore
+
+#endif // HTMLImportLoader_h
diff --git a/Source/core/platform/chromium/DragDataRef.h b/Source/core/html/HTMLImportLoaderClient.h
similarity index 84%
rename from Source/core/platform/chromium/DragDataRef.h
rename to Source/core/html/HTMLImportLoaderClient.h
index 7df3554..0cac67f 100644
--- a/Source/core/platform/chromium/DragDataRef.h
+++ b/Source/core/html/HTMLImportLoaderClient.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,15 +28,17 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef DragDataRef_h
-#define DragDataRef_h
-
-#include "core/platform/chromium/ChromiumDataObject.h"
+#ifndef HTMLImportLoaderClient_h
+#define HTMLImportLoaderClient_h
 
 namespace WebCore {
 
-    typedef ChromiumDataObject* DragDataRef;
+class HTMLImportLoaderClient {
+public:
+    virtual ~HTMLImportLoaderClient() { }
+    virtual void didFinish() = 0;
+};
 
 } // namespace WebCore
 
-#endif
+#endif // HTMLImportLoaderClient_h
diff --git a/Source/core/html/HTMLImportsController.cpp b/Source/core/html/HTMLImportsController.cpp
index daa957d..cb2107a 100644
--- a/Source/core/html/HTMLImportsController.cpp
+++ b/Source/core/html/HTMLImportsController.cpp
@@ -32,229 +32,12 @@
 #include "core/html/HTMLImportsController.h"
 
 #include "core/dom/Document.h"
-#include "core/html/HTMLDocument.h"
-#include "core/html/HTMLLinkElement.h"
-#include "core/loader/CrossOriginAccessControl.h"
-#include "core/loader/DocumentWriter.h"
-#include "core/loader/cache/CachedScript.h"
+#include "core/html/HTMLImportLoader.h"
+#include "core/html/HTMLImportLoaderClient.h"
 #include "core/loader/cache/ResourceFetcher.h"
-#include "core/page/ContentSecurityPolicyResponseHeaders.h"
-#include "weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 
-PassRefPtr<LinkImport> LinkImport::create(HTMLLinkElement* owner)
-{
-    return adoptRef(new LinkImport(owner));
-}
-
-LinkImport::LinkImport(HTMLLinkElement* owner)
-    : LinkResource(owner)
-{
-}
-
-LinkImport::~LinkImport()
-{
-}
-
-Document* LinkImport::importedDocument() const
-{
-    if (!m_loader)
-        return 0;
-    return m_loader->importedDocument();
-}
-
-void LinkImport::process()
-{
-    if (m_loader)
-        return;
-    if (!m_owner)
-        return;
-
-    if (!m_owner->document()->frame() && !m_owner->document()->import())
-        return;
-
-    LinkRequestBuilder builder(m_owner);
-    if (!builder.isValid())
-        return;
-
-    if (!m_owner->document()->import()) {
-        ASSERT(m_owner->document()->frame()); // The document should be the master.
-        HTMLImportsController::provideTo(m_owner->document());
-    }
-
-    HTMLImport* parent = m_owner->document()->import();
-    HTMLImportsController* controller = parent->controller();
-    if (RefPtr<HTMLImportLoader> found = controller->findLinkFor(builder.url())) {
-        m_loader = found;
-        return;
-    }
-
-    FetchRequest request = builder.build(true);
-    request.setPotentiallyCrossOriginEnabled(controller->securityOrigin(), DoNotAllowStoredCredentials);
-    ResourcePtr<CachedRawResource> resource = m_owner->document()->fetcher()->requestImport(request);
-    if (!resource)
-        return;
-
-    m_loader = HTMLImportLoader::create(parent, builder.url(), resource);
-}
-
-void LinkImport::ownerRemoved()
-{
-    m_owner = 0;
-    m_loader.clear();
-}
-
-
-PassRefPtr<HTMLImportLoader> HTMLImportLoader::create(HTMLImport* parent, const KURL& url, const ResourcePtr<CachedScript>& resource)
-{
-    RefPtr<HTMLImportLoader> loader = adoptRef(new HTMLImportLoader(parent, url, resource));
-    loader->controller()->addImport(loader);
-    parent->appendChild(loader.get());
-    return loader.release();
-}
-
-HTMLImportLoader::HTMLImportLoader(HTMLImport* parent, const KURL& url, const ResourcePtr<CachedScript>& resource)
-    : m_parent(parent)
-    , m_state(StateLoading)
-    , m_resource(resource)
-    , m_url(url)
-{
-    m_resource->addClient(this);
-}
-
-HTMLImportLoader::~HTMLImportLoader()
-{
-    // importDestroyed() should be called before the destruction.
-    ASSERT(!m_parent);
-    ASSERT(!m_importedDocument);
-    if (m_resource)
-        m_resource->removeClient(this);
-}
-
-void HTMLImportLoader::responseReceived(Resource*, const ResourceResponse& response)
-{
-    setState(startWritingAndParsing(response));
-}
-
-void HTMLImportLoader::dataReceived(Resource*, const char* data, int length)
-{
-    RefPtr<DocumentWriter> protectingWriter(m_writer);
-    m_writer->addData(data, length);
-}
-
-void HTMLImportLoader::notifyFinished(Resource*)
-{
-    setState(finishWriting());
-}
-
-void HTMLImportLoader::setState(State state)
-{
-    if (m_state == state)
-        return;
-
-    m_state = state;
-
-    if (m_state == StateReady || m_state == StateError || m_state == StateWritten) {
-        if (RefPtr<DocumentWriter> writer = m_writer.release())
-            writer->end();
-    }
-
-    if (m_state == StateReady || m_state == StateError)
-        dispose();
-}
-
-void HTMLImportLoader::dispose()
-{
-    if (m_resource) {
-        m_resource->removeClient(this);
-        m_resource = 0;
-    }
-
-    ASSERT(!document() || !document()->parsing());
-    controller()->scheduleUnblock();
-}
-
-HTMLImportLoader::State HTMLImportLoader::startWritingAndParsing(const ResourceResponse& response)
-{
-    // Current canAccess() implementation isn't sufficient for catching cross-domain redirects: http://crbug.com/256976
-    if (!m_parent->document()->fetcher()->canAccess(m_resource.get()))
-        return StateError;
-
-    m_importedDocument = HTMLDocument::create(DocumentInit(response.url(), 0, this).withRegistrationContext(controller()->document()->registrationContext()));
-    m_importedDocument->initContentSecurityPolicy(ContentSecurityPolicyResponseHeaders(response));
-    m_writer = DocumentWriter::create(m_importedDocument.get(), response.mimeType(), response.textEncodingName());
-
-    return StateLoading;
-}
-
-HTMLImportLoader::State HTMLImportLoader::finishWriting()
-{
-    if (!m_parent)
-        return StateError;
-    // The writer instance indicates that a part of the document can be already loaded.
-    // We don't take such a case as an error because the partially-loaded document has been visible from script at this point.
-    if (m_resource->loadFailedOrCanceled() && !m_writer)
-        return StateError;
-
-    return StateWritten;
-}
-
-HTMLImportLoader::State HTMLImportLoader::finishParsing()
-{
-    if (!m_parent)
-        return StateError;
-    return StateReady;
-}
-
-Document* HTMLImportLoader::importedDocument() const
-{
-    if (m_state == StateError)
-        return 0;
-    return m_importedDocument.get();
-}
-
-void HTMLImportLoader::importDestroyed()
-{
-    m_parent = 0;
-    if (RefPtr<Document> document = m_importedDocument.release())
-        document->setImport(0);
-}
-
-HTMLImportsController* HTMLImportLoader::controller()
-{
-    return m_parent ? m_parent->controller() : 0;
-}
-
-HTMLImport* HTMLImportLoader::parent() const
-{
-    return m_parent;
-}
-
-Document* HTMLImportLoader::document() const
-{
-    return m_importedDocument.get();
-}
-
-void HTMLImportLoader::wasDetachedFromDocument()
-{
-    // For imported documens this shouldn't be called because Document::m_import is
-    // cleared before Document is destroyed by HTMLImportLoader::importDestroyed().
-    ASSERT_NOT_REACHED();
-}
-
-void HTMLImportLoader::didFinishParsing()
-{
-    setState(finishParsing());
-}
-
-bool HTMLImportLoader::isProcessing() const
-{
-    if (!m_importedDocument)
-        return !isDone();
-    return m_importedDocument->parsing();
-}
-
 void HTMLImportsController::provideTo(Document* master)
 {
     DEFINE_STATIC_LOCAL(const char*, name, ("HTMLImportsController"));
@@ -283,10 +66,22 @@
     m_master = 0;
 }
 
-void HTMLImportsController::addImport(PassRefPtr<HTMLImportLoader> link)
+PassRefPtr<HTMLImportLoader> HTMLImportsController::createLoader(HTMLImport* parent, FetchRequest request)
 {
-    ASSERT(!link->url().isEmpty() && link->url().isValid());
-    m_imports.append(link);
+    ASSERT(!request.url().isEmpty() && request.url().isValid());
+
+    if (RefPtr<HTMLImportLoader> found = findLinkFor(request.url()))
+        return found.release();
+
+    request.setPotentiallyCrossOriginEnabled(securityOrigin(), DoNotAllowStoredCredentials);
+    ResourcePtr<RawResource> resource = parent->document()->fetcher()->requestImport(request);
+    if (!resource)
+        return 0;
+
+    RefPtr<HTMLImportLoader> loader = adoptRef(new HTMLImportLoader(parent, request.url(), resource));
+    parent->appendChild(loader.get());
+    m_imports.append(loader);
+    return loader.release();
 }
 
 void HTMLImportsController::showSecurityErrorMessage(const String& message)
@@ -314,7 +109,7 @@
     return m_master->fetcher();
 }
 
-HTMLImportsController* HTMLImportsController::controller()
+HTMLImportRoot* HTMLImportsController::root()
 {
     return this;
 }
@@ -343,6 +138,11 @@
     return m_master->parsing();
 }
 
+void HTMLImportsController::importWasDisposed()
+{
+    scheduleUnblock();
+}
+
 void HTMLImportsController::scheduleUnblock()
 {
     if (m_unblockTimer.isActive())
diff --git a/Source/core/html/HTMLImportsController.h b/Source/core/html/HTMLImportsController.h
index 3d4cee5..b106d8a 100644
--- a/Source/core/html/HTMLImportsController.h
+++ b/Source/core/html/HTMLImportsController.h
@@ -33,8 +33,7 @@
 
 #include "core/html/HTMLImport.h"
 #include "core/html/LinkResource.h"
-#include "core/loader/cache/CachedRawResource.h"
-#include "core/loader/cache/ResourcePtr.h"
+#include "core/loader/cache/RawResource.h"
 #include "core/platform/Supplementable.h"
 #include "core/platform/Timer.h"
 #include "wtf/FastAllocBase.h"
@@ -43,85 +42,13 @@
 
 namespace WebCore {
 
+class FetchRequest;
 class ScriptExecutionContext;
 class ResourceFetcher;
 class HTMLImportLoader;
-class HTMLImportsController;
-class DocumentWriter;
+class HTMLImportLoaderClient;
 
-//
-// A LinkResource subclasss used for @rel=import.
-//
-class LinkImport : public LinkResource {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-
-    static PassRefPtr<LinkImport> create(HTMLLinkElement* owner);
-
-    explicit LinkImport(HTMLLinkElement* owner);
-    virtual ~LinkImport();
-
-    // LinkResource
-    virtual void process() OVERRIDE;
-    virtual Type type() const OVERRIDE { return Import; }
-    virtual void ownerRemoved() OVERRIDE;
-
-    Document* importedDocument() const;
-
-private:
-    RefPtr<HTMLImportLoader> m_loader;
-};
-
-class HTMLImportLoader : public RefCounted<HTMLImportLoader>, public HTMLImport, public CachedRawResourceClient {
-public:
-    enum State {
-        StateLoading,
-        StateWritten,
-        StateError,
-        StateReady
-    };
-
-    static PassRefPtr<HTMLImportLoader> create(HTMLImport* parent, const KURL&, const ResourcePtr<CachedScript>&);
-    virtual ~HTMLImportLoader();
-
-    Document* importedDocument() const;
-    const KURL& url() const { return m_url; }
-
-    void importDestroyed();
-    bool isDone() const { return m_state == StateReady || m_state == StateError; }
-
-    // HTMLImport
-    virtual HTMLImportsController* controller() OVERRIDE;
-    virtual HTMLImport* parent() const OVERRIDE;
-    virtual Document* document() const OVERRIDE;
-    virtual void wasDetachedFromDocument() OVERRIDE;
-    virtual void didFinishParsing() OVERRIDE;
-    virtual bool isProcessing() const OVERRIDE;
-
-private:
-    HTMLImportLoader(HTMLImport*, const KURL&, const ResourcePtr<CachedScript>&);
-
-    // CachedRawResourceClient
-    virtual void responseReceived(Resource*, const ResourceResponse&) OVERRIDE;
-    virtual void dataReceived(Resource*, const char* data, int length) OVERRIDE;
-    virtual void notifyFinished(Resource*) OVERRIDE;
-
-    State startWritingAndParsing(const ResourceResponse&);
-    State finishWriting();
-    State finishParsing();
-
-    void setState(State);
-    void dispose();
-
-    HTMLImport* m_parent;
-    State m_state;
-    KURL m_url;
-    ResourcePtr<CachedRawResource> m_resource;
-    RefPtr<Document> m_importedDocument;
-    RefPtr<DocumentWriter> m_writer;
-};
-
-class HTMLImportsController : public HTMLImport, public Supplement<ScriptExecutionContext> {
+class HTMLImportsController : public HTMLImportRoot, public Supplement<ScriptExecutionContext> {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static void provideTo(Document*);
@@ -130,14 +57,17 @@
     virtual ~HTMLImportsController();
 
     // HTMLImport
-    virtual HTMLImportsController* controller() OVERRIDE;
+    virtual HTMLImportRoot* root() OVERRIDE;
     virtual HTMLImport* parent() const OVERRIDE;
     virtual Document* document() const OVERRIDE;
     virtual void wasDetachedFromDocument() OVERRIDE;
     virtual void didFinishParsing() OVERRIDE;
     virtual bool isProcessing() const OVERRIDE;
+    // HTMLImportRoot
+    virtual void importWasDisposed() OVERRIDE;
+    virtual HTMLImportsController* toController() { return this; }
 
-    void addImport(PassRefPtr<HTMLImportLoader>);
+    PassRefPtr<HTMLImportLoader> createLoader(HTMLImport* parent, FetchRequest);
     void showSecurityErrorMessage(const String&);
     PassRefPtr<HTMLImportLoader> findLinkFor(const KURL&) const;
     SecurityOrigin* securityOrigin() const;
diff --git a/Source/core/html/HTMLInputElement.cpp b/Source/core/html/HTMLInputElement.cpp
index 3512604..236c653 100644
--- a/Source/core/html/HTMLInputElement.cpp
+++ b/Source/core/html/HTMLInputElement.cpp
@@ -188,16 +188,6 @@
     return m_inputType->innerSpinButtonElement();
 }
 
-HTMLElement* HTMLInputElement::searchDecorationElement() const
-{
-    return m_inputType->searchDecorationElement();
-}
-
-HTMLElement* HTMLInputElement::cancelButtonElement() const
-{
-    return m_inputType->cancelButtonElement();
-}
-
 #if ENABLE(INPUT_SPEECH)
 HTMLElement* HTMLInputElement::speechButtonElement() const
 {
diff --git a/Source/core/html/HTMLInputElement.h b/Source/core/html/HTMLInputElement.h
index 268be2b..faa6b8e 100644
--- a/Source/core/html/HTMLInputElement.h
+++ b/Source/core/html/HTMLInputElement.h
@@ -122,8 +122,6 @@
     virtual HTMLElement* innerTextElement() const;
     HTMLElement* innerBlockElement() const;
     HTMLElement* innerSpinButtonElement() const;
-    HTMLElement* searchDecorationElement() const;
-    HTMLElement* cancelButtonElement() const;
 #if ENABLE(INPUT_SPEECH)
     HTMLElement* speechButtonElement() const;
 #endif
diff --git a/Source/core/html/HTMLInputElement.idl b/Source/core/html/HTMLInputElement.idl
index 2911901..fd17406 100644
--- a/Source/core/html/HTMLInputElement.idl
+++ b/Source/core/html/HTMLInputElement.idl
@@ -34,15 +34,15 @@
     // https://www.w3.org/Bugs/Public/show_bug.cgi?id=22682
     attribute FileList files;
     [Reflect, URL] attribute DOMString formAction;
-    [TreatNullAs=NullString] attribute DOMString formEnctype;
-    [TreatNullAs=NullString] attribute DOMString formMethod;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString formEnctype;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString formMethod;
     [Reflect] attribute boolean formNoValidate;
     [Reflect] attribute DOMString formTarget;
-    attribute unsigned long height;
+    [CustomElementCallbacks=Enable] attribute unsigned long height;
     attribute boolean indeterminate;
     [EnabledAtRuntime=DataListElement] readonly attribute HTMLElement list;
     [Reflect] attribute DOMString max;
-    [SetterRaisesException] attribute long maxLength;
+    [SetterRaisesException, CustomElementCallbacks=Enable] attribute long maxLength;
     [Reflect] attribute DOMString min;
     [Reflect] attribute boolean multiple;
     [Reflect] attribute DOMString name;
@@ -50,21 +50,21 @@
     [Reflect] attribute DOMString placeholder;
     [Reflect] attribute boolean readOnly;
     [Reflect] attribute boolean required;
-    [SetterRaisesException] attribute unsigned long size; // Changed string -> long -> unsigned long
+    [SetterRaisesException, CustomElementCallbacks=Enable] attribute unsigned long size; // Changed string -> long -> unsigned long
     [Reflect, URL] attribute DOMString src;
     [Reflect] attribute DOMString step;
-    [TreatNullAs=NullString] attribute DOMString type; // readonly dropped as part of DOM level 2
-    [TreatNullAs=NullString] attribute DOMString defaultValue;
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString type; // readonly dropped as part of DOM level 2
+    [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString defaultValue;
     // See the discussion in https://bugs.webkit.org/show_bug.cgi?id=100085
-    [TreatNullAs=NullString, SetterRaisesException] attribute DOMString value;
-    [SetterRaisesException] attribute Date valueAsDate;
-    [SetterRaisesException] attribute double valueAsNumber;
+    [TreatNullAs=NullString, SetterRaisesException, CustomElementCallbacks=Enable] attribute DOMString value;
+    [SetterRaisesException, CustomElementCallbacks=Enable] attribute Date valueAsDate;
+    [SetterRaisesException, CustomElementCallbacks=Enable] attribute double valueAsNumber;
     [EnabledAtRuntime=inputModeAttribute, Reflect] attribute DOMString inputMode;
 
-    [RaisesException] void stepUp(optional long n);
-    [RaisesException] void stepDown(optional long n);
+    [RaisesException, CustomElementCallbacks=Enable] void stepUp(optional long n);
+    [RaisesException, CustomElementCallbacks=Enable] void stepDown(optional long n);
 
-    attribute unsigned long width;
+    [CustomElementCallbacks=Enable] attribute unsigned long width;
     readonly attribute boolean willValidate;
     readonly attribute ValidityState validity;
     readonly attribute DOMString validationMessage;
@@ -96,7 +96,7 @@
     [Reflect] attribute boolean incremental;
     [Conditional=INPUT_SPEECH, Reflect, EnabledAtRuntime=speechInput] attribute boolean webkitSpeech;
     [Conditional=INPUT_SPEECH, Reflect, EnabledAtRuntime=speechInput] attribute boolean webkitGrammar;
-    [Conditional=INPUT_SPEECH, NotEnumerable] attribute EventListener onwebkitspeechchange;
+    [Conditional=INPUT_SPEECH, NotEnumerable] attribute EventHandler onwebkitspeechchange;
 
     // See http://www.w3.org/TR/html-media-capture/
     [Conditional=MEDIA_CAPTURE, Reflect] attribute boolean capture;
diff --git a/Source/core/html/HTMLKeygenElement.cpp b/Source/core/html/HTMLKeygenElement.cpp
index a79b7eb..590e677 100644
--- a/Source/core/html/HTMLKeygenElement.cpp
+++ b/Source/core/html/HTMLKeygenElement.cpp
@@ -59,7 +59,7 @@
 
     // Create a select element with one option element for each key size.
     RefPtr<HTMLSelectElement> select = HTMLSelectElement::create(document());
-    select->setPseudo(keygenSelectPseudoId);
+    select->setPart(keygenSelectPseudoId);
     for (size_t i = 0; i < keys.size(); ++i) {
         RefPtr<HTMLOptionElement> option = HTMLOptionElement::create(document());
         option->appendChild(Text::create(document(), keys[i]), ASSERT_NO_EXCEPTION);
diff --git a/Source/core/html/HTMLLinkElement.cpp b/Source/core/html/HTMLLinkElement.cpp
index b2e4ae6..cf9220a 100644
--- a/Source/core/html/HTMLLinkElement.cpp
+++ b/Source/core/html/HTMLLinkElement.cpp
@@ -37,10 +37,10 @@
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventSender.h"
-#include "core/html/HTMLImportsController.h"
+#include "core/html/LinkImport.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
+#include "core/loader/cache/CSSStyleSheetResource.h"
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/ContentSecurityPolicy.h"
@@ -288,13 +288,18 @@
 void HTMLLinkElement::dispatchPendingEvent(LinkEventSender* eventSender)
 {
     ASSERT_UNUSED(eventSender, eventSender == &linkLoadEventSender());
-    ASSERT(linkStyle());
-    if (linkStyle()->hasLoadedSheet())
+    ASSERT(m_link);
+    if (m_link->hasLoaded())
         linkLoaded();
     else
         linkLoadingErrored();
 }
 
+void HTMLLinkElement::scheduleEvent()
+{
+    linkLoadEventSender().dispatchEventSoon(this);
+}
+
 void HTMLLinkElement::startLoadingDynamicSheet()
 {
     ASSERT(linkStyle());
@@ -386,8 +391,8 @@
     if (m_sheet)
         m_sheet->clearOwnerNode();
 
-    if (m_cachedSheet)
-        m_cachedSheet->removeClient(this);
+    if (m_resource)
+        m_resource->removeClient(this);
 }
 
 Document* LinkStyle::document()
@@ -395,7 +400,7 @@
     return m_owner->document();
 }
 
-void LinkStyle::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CachedCSSStyleSheet* cachedStyleSheet)
+void LinkStyle::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* cachedStyleSheet)
 {
     if (!m_owner->inDocument()) {
         ASSERT(!m_sheet);
@@ -407,7 +412,7 @@
 
     CSSParserContext parserContext(m_owner->document(), baseURL, charset);
 
-    if (RefPtr<StyleSheetContents> restoredSheet = const_cast<CachedCSSStyleSheet*>(cachedStyleSheet)->restoreParsedStyleSheet(parserContext)) {
+    if (RefPtr<StyleSheetContents> restoredSheet = const_cast<CSSStyleSheetResource*>(cachedStyleSheet)->restoreParsedStyleSheet(parserContext)) {
         ASSERT(restoredSheet->isCacheable());
         ASSERT(!restoredSheet->isLoading());
 
@@ -438,7 +443,7 @@
     styleSheet->checkLoaded();
 
     if (styleSheet->isCacheable())
-        const_cast<CachedCSSStyleSheet*>(cachedStyleSheet)->saveParsedStyleSheet(styleSheet);
+        const_cast<CSSStyleSheetResource*>(cachedStyleSheet)->saveParsedStyleSheet(styleSheet);
 }
 
 bool LinkStyle::sheetLoaded()
@@ -455,7 +460,8 @@
     if (m_firedLoad)
         return;
     m_loadedSheet = !errorOccurred;
-    linkLoadEventSender().dispatchEventSoon(m_owner);
+    if (m_owner)
+        m_owner->scheduleEvent();
     m_firedLoad = true;
 }
 
@@ -579,10 +585,10 @@
     if ((m_disabledState != Disabled) && m_owner->relAttribute().isStyleSheet()
         && document()->frame() && builder.url().isValid()) {
 
-        if (m_cachedSheet) {
+        if (m_resource) {
             removePendingSheet();
-            m_cachedSheet->removeClient(this);
-            m_cachedSheet = 0;
+            m_resource->removeClient(this);
+            m_resource = 0;
         }
 
         if (!m_owner->shouldLoadLink())
@@ -605,10 +611,10 @@
 
         // Load stylesheets that are not needed for the rendering immediately with low priority.
         FetchRequest request = builder.build(blocking);
-        m_cachedSheet = document()->fetcher()->requestCSSStyleSheet(request);
+        m_resource = document()->fetcher()->requestCSSStyleSheet(request);
 
-        if (m_cachedSheet)
-            m_cachedSheet->addClient(this);
+        if (m_resource)
+            m_resource->addClient(this);
         else {
             // The request may have been denied if (for example) the stylesheet is local and the document is remote.
             m_loading = false;
diff --git a/Source/core/html/HTMLLinkElement.h b/Source/core/html/HTMLLinkElement.h
index 10c9587..9d10b26 100644
--- a/Source/core/html/HTMLLinkElement.h
+++ b/Source/core/html/HTMLLinkElement.h
@@ -32,8 +32,8 @@
 #include "core/html/LinkResource.h"
 #include "core/loader/LinkLoader.h"
 #include "core/loader/LinkLoaderClient.h"
-#include "core/loader/cache/CachedStyleSheetClient.h"
 #include "core/loader/cache/ResourcePtr.h"
+#include "core/loader/cache/StyleSheetResourceClient.h"
 
 namespace WebCore {
 
@@ -54,7 +54,7 @@
 // changing @rel makes it harder to move such a design so we are
 // sticking current way so far.
 //
-class LinkStyle FINAL : public LinkResource, CachedStyleSheetClient {
+class LinkStyle FINAL : public LinkResource, StyleSheetResourceClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassRefPtr<LinkStyle> create(HTMLLinkElement* owner);
@@ -65,6 +65,7 @@
     virtual Type type() const OVERRIDE { return Style; }
     virtual void process() OVERRIDE;
     virtual void ownerRemoved() OVERRIDE;
+    virtual bool hasLoaded() const OVERRIDE { return m_loadedSheet; }
 
     void startLoadingDynamicSheet();
     void notifyLoadedSheetAndAllCriticalSubresources(bool errorOccurred);
@@ -75,7 +76,6 @@
 
     bool styleSheetIsLoading() const;
     bool hasSheet() const { return m_sheet; }
-    bool hasLoadedSheet() const { return m_loadedSheet; }
     bool isDisabled() const { return m_disabledState == Disabled; }
     bool isEnabledViaScript() const { return m_disabledState == EnabledViaScript; }
     bool isUnset() const { return m_disabledState == Unset; }
@@ -84,7 +84,7 @@
 
 private:
     // From ResourceClient
-    virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CachedCSSStyleSheet*);
+    virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*);
 
     enum DisabledState {
         Unset,
@@ -108,7 +108,7 @@
     void removePendingSheet(RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
     Document* document();
 
-    ResourcePtr<CachedCSSStyleSheet> m_cachedSheet;
+    ResourcePtr<CSSStyleSheetResource> m_resource;
     RefPtr<CSSStyleSheet> m_sheet;
     DisabledState m_disabledState;
     PendingSheetType m_pendingSheetType;
@@ -149,6 +149,7 @@
     DOMSettableTokenList* sizes() const;
 
     void dispatchPendingEvent(LinkEventSender*);
+    void scheduleEvent();
     static void dispatchPendingLoadEvents();
 
     // From LinkLoaderClient
diff --git a/Source/core/html/HTMLMarqueeElement.idl b/Source/core/html/HTMLMarqueeElement.idl
index 9fc56be..b5bda0c 100644
--- a/Source/core/html/HTMLMarqueeElement.idl
+++ b/Source/core/html/HTMLMarqueeElement.idl
@@ -35,7 +35,7 @@
 
     // FIXME: Implement the following event handler attributes
     // https://bugs.webkit.org/show_bug.cgi?id=49788
-    // attribute EventListener onbounce;
-    // attribute EventListener onfinish;
-    // attribute EventListener onstart;
+    // attribute EventHandler onbounce;
+    // attribute EventHandler onfinish;
+    // attribute EventHandler onstart;
 };
diff --git a/Source/core/html/HTMLMediaElement.cpp b/Source/core/html/HTMLMediaElement.cpp
index 540c8e8..ba7d02b 100644
--- a/Source/core/html/HTMLMediaElement.cpp
+++ b/Source/core/html/HTMLMediaElement.cpp
@@ -188,7 +188,7 @@
 
 static bool canLoadURL(const KURL& url, const ContentType& contentType, const String& keySystem)
 {
-    DEFINE_STATIC_LOCAL(const String, codecs, (ASCIILiteral("codecs")));
+    DEFINE_STATIC_LOCAL(const String, codecs, ("codecs"));
 
     String contentMIMEType = contentType.type().lower();
     String contentTypeCodecs = contentType.parameter(codecs);
@@ -216,7 +216,7 @@
 
 WebMimeRegistry::SupportsType HTMLMediaElement::supportsType(const ContentType& contentType, const String& keySystem)
 {
-    DEFINE_STATIC_LOCAL(const String, codecs, (ASCIILiteral("codecs")));
+    DEFINE_STATIC_LOCAL(const String, codecs, ("codecs"));
 
     if (!RuntimeEnabledFeatures::mediaEnabled())
         return WebMimeRegistry::IsNotSupported;
@@ -255,6 +255,7 @@
     , m_volume(1.0f)
     , m_lastSeekTime(0)
     , m_previousProgressTime(numeric_limits<double>::max())
+    , m_duration(numeric_limits<double>::quiet_NaN())
     , m_lastTimeUpdateEventWallTime(0)
     , m_lastTimeUpdateEventMovieTime(numeric_limits<double>::max())
     , m_loadState(WaitingForSource)
@@ -619,10 +620,10 @@
             canPlay = emptyString();
             break;
         case WebMimeRegistry::MayBeSupported:
-            canPlay = ASCIILiteral("maybe");
+            canPlay = "maybe";
             break;
         case WebMimeRegistry::IsSupported:
-            canPlay = ASCIILiteral("probably");
+            canPlay = "probably";
             break;
     }
 
@@ -713,6 +714,7 @@
 
     m_playedTimeRanges = TimeRanges::create();
     m_lastSeekTime = 0;
+    m_duration = numeric_limits<double>::quiet_NaN();
 
     // The spec doesn't say to block the load event until we actually run the asynchronous section
     // algorithm, but do it now because we won't start that until after the timer fires and the
@@ -889,7 +891,7 @@
         m_mediaSource = HTMLMediaSource::lookup(url.string());
 
     if (m_mediaSource) {
-        if (m_mediaSource->attachToElement()) {
+        if (m_mediaSource->attachToElement(this)) {
             m_player->load(url, m_mediaSource);
         } else {
             // Forget our reference to the MediaSource, so we leave it alone
@@ -1894,6 +1896,8 @@
     if (noSeekRequired) {
         if (time == now) {
             scheduleEvent(eventNames().seekingEvent);
+            // FIXME: There must be a stable state before timeupdate+seeked are dispatched and seeking
+            // is reset to false. See http://crbug.com/266631
             scheduleTimeupdateEvent(false);
             scheduleEvent(eventNames().seekedEvent);
         }
@@ -2026,6 +2030,16 @@
     if (!m_player || m_readyState < HAVE_METADATA)
         return numeric_limits<double>::quiet_NaN();
 
+    // FIXME: Refactor so m_duration is kept current (in both MSE and
+    // non-MSE cases) once we have transitioned from HAVE_NOTHING ->
+    // HAVE_METADATA. Currently, m_duration may be out of date for at least MSE
+    // case because MediaSourceBase and SourceBuffer do not notify the element
+    // directly upon duration changes caused by endOfStream, remove, or append
+    // operations; rather the notification is triggered by the WebMediaPlayer
+    // implementation observing that the underlying engine has updated duration
+    // and notifying the element to consult its MediaSource for current
+    // duration. See http://crbug.com/266644
+
     if (m_mediaSource)
         return m_mediaSource->duration();
 
@@ -2112,13 +2126,13 @@
 {
     switch (m_preload) {
     case MediaPlayer::None:
-        return ASCIILiteral("none");
+        return "none";
         break;
     case MediaPlayer::MetaData:
-        return ASCIILiteral("metadata");
+        return "metadata";
         break;
     case MediaPlayer::Auto:
-        return ASCIILiteral("auto");
+        return "auto";
         break;
     }
 
@@ -3127,7 +3141,18 @@
 void HTMLMediaElement::mediaPlayerDurationChanged()
 {
     LOG(Media, "HTMLMediaElement::mediaPlayerDurationChanged");
+    durationChanged(duration());
+}
 
+void HTMLMediaElement::durationChanged(double duration)
+{
+    LOG(Media, "HTMLMediaElement::durationChanged(%f)", duration);
+
+    // Abort if duration unchanged.
+    if (m_duration == duration)
+        return;
+
+    m_duration = duration;
     scheduleEvent(eventNames().durationchangeEvent);
 
     if (hasMediaControls())
@@ -3135,10 +3160,8 @@
     if (renderer())
         renderer()->updateFromElement();
 
-    double now = currentTime();
-    double dur = duration();
-    if (now > dur)
-        seek(dur, IGNORE_EXCEPTION);
+    if (currentTime() > duration)
+        seek(duration, IGNORE_EXCEPTION);
 }
 
 void HTMLMediaElement::mediaPlayerPlaybackStateChanged()
diff --git a/Source/core/html/HTMLMediaElement.h b/Source/core/html/HTMLMediaElement.h
index a91948f..bbc957d 100644
--- a/Source/core/html/HTMLMediaElement.h
+++ b/Source/core/html/HTMLMediaElement.h
@@ -156,6 +156,8 @@
 //  Media Source.
     void closeMediaSource();
 
+    void durationChanged(double duration);
+
     void webkitGenerateKeyRequest(const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState&);
     void webkitGenerateKeyRequest(const String& keySystem, ExceptionState&);
     void webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState&);
@@ -484,6 +486,9 @@
     unsigned m_previousProgress;
     double m_previousProgressTime;
 
+    // Cached duration to suppress duplicate events if duration unchanged.
+    double m_duration;
+
     // The last time a timeupdate event was sent (wall clock).
     double m_lastTimeUpdateEventWallTime;
 
diff --git a/Source/core/html/HTMLMediaElement.idl b/Source/core/html/HTMLMediaElement.idl
index 10ebf8a..6e811ee 100644
--- a/Source/core/html/HTMLMediaElement.idl
+++ b/Source/core/html/HTMLMediaElement.idl
@@ -92,10 +92,10 @@
 [EnabledAtRuntime=legacyEncryptedMedia, RaisesException] void webkitAddKey([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, Uint8Array key, optional Uint8Array initData, [Default=NullString] optional DOMString sessionId);
 [EnabledAtRuntime=legacyEncryptedMedia, RaisesException] void webkitCancelKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, [Default=NullString] optional DOMString sessionId);
 
-[EnabledAtRuntime=legacyEncryptedMedia] attribute EventListener onwebkitkeyadded;
-[EnabledAtRuntime=legacyEncryptedMedia] attribute EventListener onwebkitkeyerror;
-[EnabledAtRuntime=legacyEncryptedMedia] attribute EventListener onwebkitkeymessage;
-[EnabledAtRuntime=legacyEncryptedMedia] attribute EventListener onwebkitneedkey;
+[EnabledAtRuntime=legacyEncryptedMedia] attribute EventHandler onwebkitkeyadded;
+[EnabledAtRuntime=legacyEncryptedMedia] attribute EventHandler onwebkitkeyerror;
+[EnabledAtRuntime=legacyEncryptedMedia] attribute EventHandler onwebkitkeymessage;
+[EnabledAtRuntime=legacyEncryptedMedia] attribute EventHandler onwebkitneedkey;
 
 [EnabledAtRuntime=encryptedMedia, Conditional=ENCRYPTED_MEDIA_V2] attribute MediaKeys mediaKeys;
 
diff --git a/Source/core/html/HTMLMediaSource.h b/Source/core/html/HTMLMediaSource.h
index 0b02672..ddf0aef 100644
--- a/Source/core/html/HTMLMediaSource.h
+++ b/Source/core/html/HTMLMediaSource.h
@@ -31,6 +31,7 @@
 #ifndef HTMLMediaSource_h
 #define HTMLMediaSource_h
 
+#include "core/html/HTMLMediaElement.h"
 #include "core/html/URLRegistry.h"
 #include "wtf/Forward.h"
 
@@ -52,7 +53,9 @@
     // If already attached, returns false. Otherwise, must be in
     // 'closed' state, and returns true to indicate attachment success.
     // Reattachment allowed by first calling close() (even if already in 'closed').
-    virtual bool attachToElement() = 0;
+    // Once attached, the source uses the element to synchronously service some
+    // API operations like duration change that may need to initiate seek.
+    virtual bool attachToElement(HTMLMediaElement*) = 0;
     virtual void setPrivateAndOpen(PassOwnPtr<MediaSourcePrivate>) = 0;
     virtual void close() = 0;
     virtual bool isClosed() const = 0;
diff --git a/Source/core/html/HTMLObjectElement.cpp b/Source/core/html/HTMLObjectElement.cpp
index 12e6f8a..0dd38fd 100644
--- a/Source/core/html/HTMLObjectElement.cpp
+++ b/Source/core/html/HTMLObjectElement.cpp
@@ -37,7 +37,7 @@
 #include "core/html/HTMLMetaElement.h"
 #include "core/html/HTMLParamElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
diff --git a/Source/core/html/HTMLPlugInElement.cpp b/Source/core/html/HTMLPlugInElement.cpp
index 14ba749..2f1c8b7 100644
--- a/Source/core/html/HTMLPlugInElement.cpp
+++ b/Source/core/html/HTMLPlugInElement.cpp
@@ -79,6 +79,13 @@
     return true;
 }
 
+void HTMLPlugInElement::removeAllEventListeners()
+{
+    HTMLFrameOwnerElement::removeAllEventListeners();
+    if (Widget* widget = pluginWidget())
+        widget->eventListenersRemoved();
+}
+
 void HTMLPlugInElement::detach(const AttachContext& context)
 {
     m_instance.clear();
diff --git a/Source/core/html/HTMLPlugInElement.h b/Source/core/html/HTMLPlugInElement.h
index f6a4563..9584710 100644
--- a/Source/core/html/HTMLPlugInElement.h
+++ b/Source/core/html/HTMLPlugInElement.h
@@ -66,6 +66,8 @@
 
     virtual bool isPlugInImageElement() const { return false; }
 
+    virtual void removeAllEventListeners() OVERRIDE;
+
 protected:
     HTMLPlugInElement(const QualifiedName& tagName, Document*);
 
diff --git a/Source/core/html/HTMLTextAreaElement.cpp b/Source/core/html/HTMLTextAreaElement.cpp
index fae5d5d..03dd058 100644
--- a/Source/core/html/HTMLTextAreaElement.cpp
+++ b/Source/core/html/HTMLTextAreaElement.cpp
@@ -59,7 +59,7 @@
 // This function returns number of characters considering this.
 static inline unsigned computeLengthForSubmission(const String& text, unsigned numberOfLineBreaks)
 {
-    return numGraphemeClusters(text) + numberOfLineBreaks;
+    return text.length() + numberOfLineBreaks;
 }
 
 static unsigned numberOfLineBreaks(const String& text)
@@ -75,12 +75,7 @@
 
 static inline unsigned computeLengthForSubmission(const String& text)
 {
-    return numGraphemeClusters(text) + numberOfLineBreaks(text);
-}
-
-static inline unsigned upperBoundForLengthForSubmission(const String& text, unsigned numberOfLineBreaks)
-{
-    return text.length() + numberOfLineBreaks;
+    return text.length() + numberOfLineBreaks(text);
 }
 
 HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
@@ -294,12 +289,10 @@
     unsigned unsignedMaxLength = static_cast<unsigned>(signedMaxLength);
 
     const String& currentValue = innerTextValue();
-    unsigned numberOfLineBreaksInCurrentValue = numberOfLineBreaks(currentValue);
-    if (upperBoundForLengthForSubmission(currentValue, numberOfLineBreaksInCurrentValue)
-        + upperBoundForLengthForSubmission(event->text(), numberOfLineBreaks(event->text())) < unsignedMaxLength)
+    unsigned currentLength = computeLengthForSubmission(currentValue);
+    if (currentLength + computeLengthForSubmission(event->text()) < unsignedMaxLength)
         return;
 
-    unsigned currentLength = computeLengthForSubmission(currentValue, numberOfLineBreaksInCurrentValue);
     // selectionLength represents the selection length of this text field to be
     // removed by this insertion.
     // If the text field has no focus, we don't need to take account of the
@@ -314,7 +307,9 @@
 
 String HTMLTextAreaElement::sanitizeUserInputValue(const String& proposedValue, unsigned maxLength)
 {
-    return proposedValue.left(numCharactersInGraphemeClusters(proposedValue, maxLength));
+    if (maxLength > 0 && U16_IS_LEAD(proposedValue[maxLength - 1]))
+        --maxLength;
+    return proposedValue.left(maxLength);
 }
 
 HTMLElement* HTMLTextAreaElement::innerTextElement() const
@@ -484,10 +479,7 @@
     int max = maxLength();
     if (max < 0)
         return false;
-    unsigned unsignedMax = static_cast<unsigned>(max);
-    unsigned numberOfLineBreaksInValue = numberOfLineBreaks(value);
-    return upperBoundForLengthForSubmission(value, numberOfLineBreaksInValue) > unsignedMax
-        && computeLengthForSubmission(value, numberOfLineBreaksInValue) > unsignedMax;
+    return computeLengthForSubmission(value) > static_cast<unsigned>(max);
 }
 
 bool HTMLTextAreaElement::isValidValue(const String& candidate) const
@@ -549,7 +541,7 @@
     if (!m_placeholder) {
         RefPtr<HTMLDivElement> placeholder = HTMLDivElement::create(document());
         m_placeholder = placeholder.get();
-        m_placeholder->setPseudo(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+        m_placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
         userAgentShadowRoot()->insertBefore(m_placeholder, innerTextElement()->nextSibling(), ASSERT_NO_EXCEPTION);
     }
     m_placeholder->setInnerText(placeholderText, ASSERT_NO_EXCEPTION);
diff --git a/Source/core/html/HTMLVideoElement.cpp b/Source/core/html/HTMLVideoElement.cpp
index 2c6b0fa..a5590d2 100644
--- a/Source/core/html/HTMLVideoElement.cpp
+++ b/Source/core/html/HTMLVideoElement.cpp
@@ -79,7 +79,7 @@
             m_imageLoader = adoptPtr(new HTMLImageLoader(this));
         m_imageLoader->updateFromElement();
         if (renderer())
-            toRenderImage(renderer())->imageResource()->setCachedImage(m_imageLoader->image());
+            toRenderImage(renderer())->imageResource()->setImageResource(m_imageLoader->image());
     }
 }
 
@@ -112,7 +112,7 @@
             m_imageLoader->updateFromElementIgnoringPreviousError();
         } else {
             if (renderer())
-                toRenderImage(renderer())->imageResource()->setCachedImage(0);
+                toRenderImage(renderer())->imageResource()->setImageResource(0);
         }
     } else
         HTMLMediaElement::parseAttribute(name, value);
diff --git a/Source/core/html/ImageDocument.cpp b/Source/core/html/ImageDocument.cpp
index 6839e1e..64a0dc1 100644
--- a/Source/core/html/ImageDocument.cpp
+++ b/Source/core/html/ImageDocument.cpp
@@ -39,7 +39,7 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
@@ -124,7 +124,7 @@
 void ImageDocumentParser::finish()
 {
     if (!isStopped() && document()->imageElement()) {
-        CachedImage* cachedImage = document()->cachedImage();
+        ImageResource* cachedImage = document()->cachedImage();
         cachedImage->finish();
         cachedImage->setResponse(document()->frame()->loader()->documentLoader()->response());
 
@@ -338,7 +338,7 @@
     }
 }
 
-CachedImage* ImageDocument::cachedImage()
+ImageResource* ImageDocument::cachedImage()
 {
     if (!m_imageElement)
         createDocumentStructure();
diff --git a/Source/core/html/ImageDocument.h b/Source/core/html/ImageDocument.h
index fbe9e50..9400112 100644
--- a/Source/core/html/ImageDocument.h
+++ b/Source/core/html/ImageDocument.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class CachedImage;
+class ImageResource;
 class HTMLImageElement;
 
 class ImageDocument FINAL : public HTMLDocument {
@@ -40,7 +40,7 @@
         return adoptRef(new ImageDocument(initializer));
     }
 
-    CachedImage* cachedImage();
+    ImageResource* cachedImage();
     HTMLImageElement* imageElement() const { return m_imageElement.get(); }
 
     void windowSizeChanged();
diff --git a/Source/core/html/ImageInputType.cpp b/Source/core/html/ImageInputType.cpp
index 64ba937..2ad3d90 100644
--- a/Source/core/html/ImageInputType.cpp
+++ b/Source/core/html/ImageInputType.cpp
@@ -31,7 +31,7 @@
 #include "core/html/HTMLInputElement.h"
 #include "core/html/InputTypeNames.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/RenderImage.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -70,8 +70,8 @@
         return true;
     }
 
-    DEFINE_STATIC_LOCAL(String, dotXString, (ASCIILiteral(".x")));
-    DEFINE_STATIC_LOCAL(String, dotYString, (ASCIILiteral(".y")));
+    DEFINE_STATIC_LOCAL(String, dotXString, (".x"));
+    DEFINE_STATIC_LOCAL(String, dotYString, (".y"));
     encoding.appendData(name + dotXString, m_clickLocation.x());
     encoding.appendData(name + dotYString, m_clickLocation.y());
 
@@ -138,7 +138,7 @@
         return;
 
     RenderImageResource* imageResource = renderer->imageResource();
-    imageResource->setCachedImage(imageLoader->image());
+    imageResource->setImageResource(imageLoader->image());
 
     // If we have no image at all because we have no src attribute, set
     // image height and width for the alt text instead.
diff --git a/Source/core/html/InputType.cpp b/Source/core/html/InputType.cpp
index c70bf2e..940982f 100644
--- a/Source/core/html/InputType.cpp
+++ b/Source/core/html/InputType.cpp
@@ -474,12 +474,6 @@
     }
 }
 
-Element* InputType::elementById(const AtomicString& id) const
-{
-    ShadowRoot* shadowRoot = element()->userAgentShadowRoot();
-    return shadowRoot ? shadowRoot->getElementById(id) : 0;
-}
-
 Decimal InputType::parseToNumber(const String&, const Decimal& defaultValue) const
 {
     ASSERT_NOT_REACHED();
diff --git a/Source/core/html/InputType.h b/Source/core/html/InputType.h
index f7fc51c..ab9d248 100644
--- a/Source/core/html/InputType.h
+++ b/Source/core/html/InputType.h
@@ -208,14 +208,11 @@
 
     virtual void createShadowSubtree();
     virtual void destroyShadowSubtree();
-    Element* elementById(const AtomicString& id) const;
 
     virtual HTMLElement* containerElement() const { return 0; }
     virtual HTMLElement* innerBlockElement() const { return 0; }
     virtual HTMLElement* innerTextElement() const { return 0; }
     virtual HTMLElement* innerSpinButtonElement() const { return 0; }
-    virtual HTMLElement* searchDecorationElement() const { return 0; }
-    virtual HTMLElement* cancelButtonElement() const { return 0; }
 #if ENABLE(INPUT_SPEECH)
     virtual HTMLElement* speechButtonElement() const { return 0; }
 #endif
diff --git a/Source/core/html/LinkImport.cpp b/Source/core/html/LinkImport.cpp
new file mode 100644
index 0000000..31703ac
--- /dev/null
+++ b/Source/core/html/LinkImport.cpp
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/LinkImport.h"
+
+#include "core/dom/Document.h"
+#include "core/html/HTMLImportLoader.h"
+#include "core/html/HTMLImportsController.h"
+#include "core/html/HTMLLinkElement.h"
+#include "core/loader/CrossOriginAccessControl.h"
+
+namespace WebCore {
+
+PassRefPtr<LinkImport> LinkImport::create(HTMLLinkElement* owner)
+{
+    return adoptRef(new LinkImport(owner));
+}
+
+LinkImport::LinkImport(HTMLLinkElement* owner)
+    : LinkResource(owner)
+{
+}
+
+LinkImport::~LinkImport()
+{
+    clear();
+}
+
+Document* LinkImport::importedDocument() const
+{
+    if (!m_loader)
+        return 0;
+    return m_loader->importedDocument();
+}
+
+void LinkImport::process()
+{
+    if (m_loader)
+        return;
+    if (!m_owner)
+        return;
+    if (!m_owner->document()->frame() && !m_owner->document()->import())
+        return;
+
+    if (!m_owner->document()->import()) {
+        ASSERT(m_owner->document()->frame()); // The document should be the master.
+        HTMLImportsController::provideTo(m_owner->document());
+    }
+
+    LinkRequestBuilder builder(m_owner);
+    if (!builder.isValid()) {
+        didFinish();
+        return;
+    }
+
+    HTMLImport* parent = m_owner->document()->import();
+    HTMLImportsController* controller = parent->controller();
+    m_loader = controller->createLoader(parent, builder.build(true));
+    if (!m_loader) {
+        didFinish();
+        return;
+    }
+
+    m_loader->addClient(this);
+}
+
+void LinkImport::clear()
+{
+    m_owner = 0;
+
+    if (m_loader) {
+        m_loader->removeClient(this);
+        m_loader.clear();
+    }
+}
+
+void LinkImport::ownerRemoved()
+{
+    clear();
+}
+
+void LinkImport::didFinish()
+{
+    if (!m_owner)
+        return;
+    m_owner->scheduleEvent();
+}
+
+bool LinkImport::hasLoaded() const
+{
+    return m_loader && m_loader->isLoaded();
+}
+
+} // namespace WebCore
diff --git a/Source/core/loader/cache/MockCachedImageClient.h b/Source/core/html/LinkImport.h
similarity index 61%
copy from Source/core/loader/cache/MockCachedImageClient.h
copy to Source/core/html/LinkImport.h
index e9729d5..4003f88 100644
--- a/Source/core/loader/cache/MockCachedImageClient.h
+++ b/Source/core/html/LinkImport.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,45 +28,48 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef MockCachedImageClient_h
-#define MockCachedImageClient_h
+#ifndef LinkImport_h
+#define LinkImport_h
 
-#include "core/loader/cache/CachedImageClient.h"
-#include "core/page/Frame.h"
-#include "core/platform/graphics/Image.h"
-
-#include <gtest/gtest.h>
+#include "core/html/HTMLImportLoaderClient.h"
+#include "core/html/LinkResource.h"
+#include "wtf/FastAllocBase.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
-class MockCachedImageClient : public WebCore::CachedImageClient {
+class Document;
+class HTMLImportLoader;
+
+//
+// A LinkResource subclasss used for @rel=import.
+//
+class LinkImport : public LinkResource, public HTMLImportLoaderClient {
+    WTF_MAKE_FAST_ALLOCATED;
 public:
-    MockCachedImageClient()
-        : m_imageChangedCount(0)
-        , m_notifyFinishedCalled(false)
-    {
-    }
 
-    virtual ~MockCachedImageClient() { }
-    virtual void imageChanged(CachedImage*, const IntRect*)
-    {
-        m_imageChangedCount++;
-    }
+    static PassRefPtr<LinkImport> create(HTMLLinkElement* owner);
 
-    virtual void notifyFinished(Resource*)
-    {
-        ASSERT_FALSE(m_notifyFinishedCalled);
-        m_notifyFinishedCalled = true;
-    }
+    explicit LinkImport(HTMLLinkElement* owner);
+    virtual ~LinkImport();
 
-    int imageChangedCount() const { return m_imageChangedCount; }
-    bool notifyFinishedCalled() const { return m_notifyFinishedCalled; }
+    // LinkResource
+    virtual void process() OVERRIDE;
+    virtual Type type() const OVERRIDE { return Import; }
+    virtual void ownerRemoved() OVERRIDE;
+    virtual bool hasLoaded() const OVERRIDE;
+
+    // HTMLImportLoaderClient
+    virtual void didFinish() OVERRIDE;
+
+    Document* importedDocument() const;
 
 private:
-    int m_imageChangedCount;
-    bool m_notifyFinishedCalled;
+    void clear();
+
+    RefPtr<HTMLImportLoader> m_loader;
 };
 
 } // namespace WebCore
 
-#endif // CachedImageTest_h
+#endif // LinkImport_h
diff --git a/Source/core/html/LinkResource.h b/Source/core/html/LinkResource.h
index 0a8b2a8..8c6c84e 100644
--- a/Source/core/html/LinkResource.h
+++ b/Source/core/html/LinkResource.h
@@ -53,6 +53,7 @@
     virtual Type type() const = 0;
     virtual void process() = 0;
     virtual void ownerRemoved() = 0;
+    virtual bool hasLoaded() const = 0;
 
 protected:
     HTMLLinkElement* m_owner;
diff --git a/Source/core/html/RangeInputType.cpp b/Source/core/html/RangeInputType.cpp
index 8ede620..d65d553 100644
--- a/Source/core/html/RangeInputType.cpp
+++ b/Source/core/html/RangeInputType.cpp
@@ -247,7 +247,7 @@
 
     Document* document = element()->document();
     RefPtr<HTMLDivElement> track = HTMLDivElement::create(document);
-    track->setPseudo(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
+    track->setPart(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
     track->appendChild(SliderThumbElement::create(document), IGNORE_EXCEPTION);
     RefPtr<HTMLElement> container = SliderContainerElement::create(document);
     container->appendChild(track.release(), IGNORE_EXCEPTION);
@@ -332,7 +332,7 @@
     m_tickMarkValuesDirty = true;
     HTMLElement* sliderTrackElement = sliderTrackElementOf(element());
     if (sliderTrackElement->renderer())
-        sliderTrackElement->renderer()->setNeedsLayout(true);
+        sliderTrackElement->renderer()->setNeedsLayout();
 }
 
 static bool decimalCompare(const Decimal& a, const Decimal& b)
diff --git a/Source/core/html/SearchInputType.cpp b/Source/core/html/SearchInputType.cpp
index d17d432..3982770 100644
--- a/Source/core/html/SearchInputType.cpp
+++ b/Source/core/html/SearchInputType.cpp
@@ -36,6 +36,7 @@
 #include "core/dom/KeyboardEvent.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/InputTypeNames.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/TextControlInnerElements.h"
 #include "core/rendering/RenderSearchField.h"
 #include "wtf/PassOwnPtr.h"
@@ -46,8 +47,6 @@
 
 inline SearchInputType::SearchInputType(HTMLInputElement* element)
     : BaseTextInputType(element)
-    , m_searchDecoration(0)
-    , m_cancelButton(0)
     , m_searchEventTimer(this, &SearchInputType::searchEventTimerFired)
 {
 }
@@ -90,32 +89,14 @@
 
 void SearchInputType::createShadowSubtree()
 {
-    ASSERT(!m_searchDecoration);
-    ASSERT(!m_cancelButton);
-
     TextFieldInputType::createShadowSubtree();
     HTMLElement* container = containerElement();
     HTMLElement* textWrapper = innerBlockElement();
     ASSERT(container);
     ASSERT(textWrapper);
 
-    RefPtr<SearchFieldDecorationElement> searchDecoration = SearchFieldDecorationElement::create(element()->document());
-    m_searchDecoration = searchDecoration.get();
-    container->insertBefore(m_searchDecoration, textWrapper, IGNORE_EXCEPTION);
-
-    RefPtr<SearchFieldCancelButtonElement> cancelButton = SearchFieldCancelButtonElement::create(element()->document());
-    m_cancelButton = cancelButton.get();
-    container->insertBefore(m_cancelButton, textWrapper->nextSibling(), IGNORE_EXCEPTION);
-}
-
-HTMLElement* SearchInputType::searchDecorationElement() const
-{
-    return m_searchDecoration;
-}
-
-HTMLElement* SearchInputType::cancelButtonElement() const
-{
-    return m_cancelButton;
+    container->insertBefore(SearchFieldDecorationElement::create(element()->document()), textWrapper, IGNORE_EXCEPTION);
+    container->insertBefore(SearchFieldCancelButtonElement::create(element()->document()), textWrapper->nextSibling(), IGNORE_EXCEPTION);
 }
 
 void SearchInputType::handleKeydownEvent(KeyboardEvent* event)
@@ -136,13 +117,6 @@
     TextFieldInputType::handleKeydownEvent(event);
 }
 
-void SearchInputType::destroyShadowSubtree()
-{
-    TextFieldInputType::destroyShadowSubtree();
-    m_searchDecoration = 0;
-    m_cancelButton = 0;
-}
-
 void SearchInputType::startSearchEventTimer()
 {
     ASSERT(element()->renderer());
@@ -176,7 +150,7 @@
 
 void SearchInputType::didSetValueByUserEdit(ValueChangeState state)
 {
-    if (m_cancelButton)
+    if (element()->uaShadowElementById(ShadowElementNames::clearButton()))
         toRenderSearchField(element()->renderer())->updateCancelButtonVisibility();
 
     // If the incremental attribute is set, then dispatch the search event
diff --git a/Source/core/html/SearchInputType.h b/Source/core/html/SearchInputType.h
index 33a2c0a..2065c39 100644
--- a/Source/core/html/SearchInputType.h
+++ b/Source/core/html/SearchInputType.h
@@ -54,9 +54,6 @@
     virtual bool isSearchField() const OVERRIDE;
     virtual bool needsContainer() const OVERRIDE;
     virtual void createShadowSubtree() OVERRIDE;
-    virtual void destroyShadowSubtree() OVERRIDE;
-    virtual HTMLElement* searchDecorationElement() const OVERRIDE;
-    virtual HTMLElement* cancelButtonElement() const OVERRIDE;
     virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
     virtual void didSetValueByUserEdit(ValueChangeState) OVERRIDE;
     virtual bool supportsInputModeAttribute() const OVERRIDE;
@@ -64,9 +61,9 @@
     void searchEventTimerFired(Timer<SearchInputType>*);
     bool searchEventsShouldBeDispatched() const;
     void startSearchEventTimer();
+    HTMLElement* searchDecorationElement() const;
+    HTMLElement* cancelButtonElement() const;
 
-    HTMLElement* m_searchDecoration;
-    HTMLElement* m_cancelButton;
     Timer<SearchInputType> m_searchEventTimer;
 };
 
diff --git a/Source/core/html/TextFieldInputType.cpp b/Source/core/html/TextFieldInputType.cpp
index 6c51162..9b127b0 100644
--- a/Source/core/html/TextFieldInputType.cpp
+++ b/Source/core/html/TextFieldInputType.cpp
@@ -252,7 +252,7 @@
 
     ShadowRoot* shadowRoot = element()->userAgentShadowRoot();
     m_container = TextControlInnerContainer::create(document);
-    m_container->setPseudo(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
+    m_container->setPart(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
     shadowRoot->appendChild(m_container, IGNORE_EXCEPTION);
 
     m_innerBlock = TextControlInnerElement::create(document);
@@ -357,7 +357,9 @@
 
 static String limitLength(const String& string, int maxLength)
 {
-    unsigned newLength = numCharactersInGraphemeClusters(string, maxLength);
+    unsigned newLength = maxLength;
+    // FIXME: We should not truncate the string at a control character. It's not
+    // compatible with IE and Firefox.
     for (unsigned i = 0; i < newLength; ++i) {
         const UChar current = string[i];
         if (current < ' ' && current != '\t') {
@@ -365,6 +367,8 @@
             break;
         }
     }
+    if (newLength > 0 && U16_IS_LEAD(string[newLength - 1]))
+        --newLength;
     return string.left(newLength);
 }
 
@@ -377,17 +381,17 @@
 {
     // Make sure that the text to be inserted will not violate the maxLength.
 
-    // We use RenderTextControlSingleLine::text() instead of InputElement::value()
-    // because they can be mismatched by sanitizeValue() in
-    // HTMLInputElement::subtreeHasChanged() in some cases.
-    unsigned oldLength = numGraphemeClusters(element()->innerTextValue());
+    // We use HTMLInputElement::innerTextValue() instead of
+    // HTMLInputElement::value() because they can be mismatched by
+    // sanitizeValue() in HTMLInputElement::subtreeHasChanged() in some cases.
+    unsigned oldLength = element()->innerTextValue().length();
 
     // selectionLength represents the selection length of this text field to be
     // removed by this insertion.
     // If the text field has no focus, we don't need to take account of the
     // selection length. The selection is the source of text drag-and-drop in
     // that case, and nothing in the text field will be removed.
-    unsigned selectionLength = element()->focused() ? numGraphemeClusters(plainText(element()->document()->frame()->selection()->selection().toNormalizedRange().get())) : 0;
+    unsigned selectionLength = element()->focused() ? plainText(element()->document()->frame()->selection()->selection().toNormalizedRange().get()).length() : 0;
     ASSERT(oldLength >= selectionLength);
 
     // Selected characters will be removed by the next text event.
@@ -427,7 +431,7 @@
     }
     if (!m_placeholder) {
         m_placeholder = HTMLDivElement::create(element()->document());
-        m_placeholder->setPseudo(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+        m_placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
         element()->userAgentShadowRoot()->insertBefore(m_placeholder, m_container ? m_container->nextSibling() : innerTextElement()->nextSibling(), ASSERT_NO_EXCEPTION);
     }
     m_placeholder->setInnerText(placeholderText, ASSERT_NO_EXCEPTION);
diff --git a/Source/core/html/canvas/CanvasRenderingContext.cpp b/Source/core/html/canvas/CanvasRenderingContext.cpp
index fa64846..71580c9 100644
--- a/Source/core/html/canvas/CanvasRenderingContext.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext.cpp
@@ -30,7 +30,7 @@
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/canvas/CanvasPattern.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "weborigin/SecurityOrigin.h"
 
 namespace WebCore {
@@ -60,7 +60,7 @@
     if (!image || !canvas()->originClean())
         return false;
 
-    CachedImage* cachedImage = image->cachedImage();
+    ImageResource* cachedImage = image->cachedImage();
     if (!cachedImage->image()->hasSingleSecurityOrigin())
         return true;
 
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index 0b22f93..feff097 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -53,7 +53,7 @@
 #include "core/html/canvas/CanvasPattern.h"
 #include "core/html/canvas/CanvasStyle.h"
 #include "core/html/canvas/DOMPath.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/ImageBitmap.h"
 #include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/FloatQuad.h"
@@ -78,7 +78,7 @@
 static const char* const defaultFontFamily = "sans-serif";
 static const char* const defaultFont = "10px sans-serif";
 
-static bool isOriginClean(CachedImage* cachedImage, SecurityOrigin* securityOrigin)
+static bool isOriginClean(ImageResource* cachedImage, SecurityOrigin* securityOrigin)
 {
     if (!cachedImage->image()->hasSingleSecurityOrigin())
         return false;
@@ -1171,14 +1171,14 @@
     return alphaChannel(state().m_shadowColor) && (state().m_shadowBlur || !state().m_shadowOffset.isZero());
 }
 
-static LayoutSize size(HTMLImageElement* image)
+static LayoutSize sizeFor(HTMLImageElement* image)
 {
-    if (CachedImage* cachedImage = image->cachedImage())
+    if (ImageResource* cachedImage = image->cachedImage())
         return cachedImage->imageSizeForRenderer(image->renderer(), 1.0f); // FIXME: Not sure about this.
     return IntSize();
 }
 
-static IntSize size(HTMLVideoElement* video)
+static IntSize sizeFor(HTMLVideoElement* video)
 {
     if (MediaPlayer* player = video->player())
         return player->naturalSize();
@@ -1294,9 +1294,10 @@
 
     FloatRect intersectRect = intersection(bitmapRect, normalizedSrcRect);
     FloatRect actualSrcRect(intersectRect);
-    actualSrcRect.move(-bitmapRect.x(), -bitmapRect.y());
 
-    FloatRect imageRect = FloatRect(FloatPoint(), bitmapRect.size());
+    IntPoint bitmapOffset = bitmap->bitmapOffset();
+    actualSrcRect.move(bitmapOffset - bitmapRect.location());
+    FloatRect imageRect = FloatRect(bitmapOffset, bitmapRect.size());
 
     FloatRect actualDstRect(FloatPoint(intersectRect.location() - normalizedSrcRect.location()), bitmapRect.size());
     actualDstRect.scale(normalizedDstRect.width() / normalizedSrcRect.width() * intersectRect.width() / bitmapRect.width(),
@@ -1316,8 +1317,8 @@
         es.throwDOMException(TypeMismatchError);
         return;
     }
-    LayoutSize s = size(image);
-    drawImage(image, x, y, s.width(), s.height(), es);
+    LayoutSize size = sizeFor(image);
+    drawImage(image, x, y, size.width(), size.height(), es);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLImageElement* image,
@@ -1327,8 +1328,8 @@
         es.throwDOMException(TypeMismatchError);
         return;
     }
-    LayoutSize s = size(image);
-    drawImage(image, FloatRect(0, 0, s.width(), s.height()), FloatRect(x, y, width, height), es);
+    LayoutSize size = sizeFor(image);
+    drawImage(image, FloatRect(0, 0, size.width(), size.height()), FloatRect(x, y, width, height), es);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLImageElement* image,
@@ -1354,16 +1355,23 @@
         || !std::isfinite(srcRect.x()) || !std::isfinite(srcRect.y()) || !std::isfinite(srcRect.width()) || !std::isfinite(srcRect.height()))
         return;
 
-    if (!dstRect.width() || !dstRect.height())
+    ImageResource* cachedImage = image->cachedImage();
+    if (!cachedImage || !image->complete())
         return;
 
-    if (!image->complete())
+    LayoutSize size = sizeFor(image);
+    if (!size.width() || !size.height()) {
+        es.throwDOMException(InvalidStateError);
+        return;
+    }
+
+    if (!dstRect.width() || !dstRect.height())
         return;
 
     FloatRect normalizedSrcRect = normalizeRect(srcRect);
     FloatRect normalizedDstRect = normalizeRect(dstRect);
 
-    FloatRect imageRect = FloatRect(FloatPoint(), size(image));
+    FloatRect imageRect = FloatRect(FloatPoint(), size);
     if (!srcRect.width() || !srcRect.height()) {
         es.throwDOMException(IndexSizeError);
         return;
@@ -1373,10 +1381,6 @@
 
     clipRectsToImageRect(imageRect, &normalizedSrcRect, &normalizedDstRect);
 
-    CachedImage* cachedImage = image->cachedImage();
-    if (!cachedImage)
-        return;
-
     checkOrigin(image);
 
     Image* imageForRendering = cachedImage->imageForRenderer(image->renderer());
@@ -1478,8 +1482,8 @@
         es.throwDOMException(TypeMismatchError);
         return;
     }
-    IntSize s = size(video);
-    drawImage(video, x, y, s.width(), s.height(), es);
+    IntSize size = sizeFor(video);
+    drawImage(video, x, y, size.width(), size.height(), es);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video,
@@ -1489,8 +1493,8 @@
         es.throwDOMException(TypeMismatchError);
         return;
     }
-    IntSize s = size(video);
-    drawImage(video, FloatRect(0, 0, s.width(), s.height()), FloatRect(x, y, width, height), es);
+    IntSize size = sizeFor(video);
+    drawImage(video, FloatRect(0, 0, size.width(), size.height()), FloatRect(x, y, width, height), es);
 }
 
 void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video,
@@ -1510,7 +1514,7 @@
     if (video->readyState() == HTMLMediaElement::HAVE_NOTHING || video->readyState() == HTMLMediaElement::HAVE_METADATA)
         return;
 
-    FloatRect videoRect = FloatRect(FloatPoint(), size(video));
+    FloatRect videoRect = FloatRect(FloatPoint(), sizeFor(video));
     if (!srcRect.width() || !srcRect.height()) {
         es.throwDOMException(IndexSizeError);
         return;
@@ -1537,7 +1541,7 @@
     c->translate(normalizedDstRect.x(), normalizedDstRect.y());
     c->scale(FloatSize(normalizedDstRect.width() / normalizedSrcRect.width(), normalizedDstRect.height() / normalizedSrcRect.height()));
     c->translate(-normalizedSrcRect.x(), -normalizedSrcRect.y());
-    video->paintCurrentFrameInContext(c, IntRect(IntPoint(), size(video)));
+    video->paintCurrentFrameInContext(c, IntRect(IntPoint(), sizeFor(video)));
     stateSaver.restore();
     didDraw(dstRect);
 }
@@ -1748,7 +1752,7 @@
     if (!image->complete())
         return 0;
 
-    CachedImage* cachedImage = image->cachedImage();
+    ImageResource* cachedImage = image->cachedImage();
     Image* imageForRendering = cachedImage ? cachedImage->imageForRenderer(image->renderer()) : 0;
     if (!imageForRendering)
         return CanvasPattern::create(Image::nullImage(), repeatX, repeatY, true);
@@ -1892,7 +1896,7 @@
 PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(ImageBuffer::CoordinateSystem coordinateSystem, float sx, float sy, float sw, float sh, ExceptionState& es) const
 {
     if (!canvas()->originClean()) {
-        DEFINE_STATIC_LOCAL(String, consoleMessage, (ASCIILiteral("Unable to get image data from canvas because the canvas has been tainted by cross-origin data.")));
+        DEFINE_STATIC_LOCAL(String, consoleMessage, ("Unable to get image data from canvas because the canvas has been tainted by cross-origin data."));
         canvas()->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
         es.throwDOMException(SecurityError);
         return 0;
@@ -2051,13 +2055,13 @@
 
 void CanvasRenderingContext2D::setFont(const String& newFont)
 {
-    MutableStylePropertyMap::iterator i = m_cachedFonts.find(newFont);
-    RefPtr<MutableStylePropertySet> parsedStyle = i != m_cachedFonts.end() ? i->value : 0;
+    MutableStylePropertyMap::iterator i = m_fetchedFonts.find(newFont);
+    RefPtr<MutableStylePropertySet> parsedStyle = i != m_fetchedFonts.end() ? i->value : 0;
 
     if (!parsedStyle) {
         parsedStyle = MutableStylePropertySet::create();
         CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, newFont, true, strictToCSSParserMode(!m_usesCSSCompatibilityParseMode), 0);
-        m_cachedFonts.add(newFont, parsedStyle);
+        m_fetchedFonts.add(newFont, parsedStyle);
     }
     if (parsedStyle->isEmpty())
         return;
@@ -2342,7 +2346,10 @@
         return;
 
     updateFocusRingAccessibility(m_path, element);
-    if (element->focused())
+    // Note: we need to check document->focusedElement() rather than just calling
+    // element->focused(), because element->focused() isn't updated until after
+    // focus events fire.
+    if (element->document() && element->document()->focusedElement() == element)
         drawFocusRing(m_path);
 }
 
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.h b/Source/core/html/canvas/CanvasRenderingContext2D.h
index 7d9218d..a76a954 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.h
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.h
@@ -341,7 +341,7 @@
     unsigned m_unrealizedSaveCount;
     bool m_usesCSSCompatibilityParseMode;
     bool m_hasAlpha;
-    MutableStylePropertyMap m_cachedFonts;
+    MutableStylePropertyMap m_fetchedFonts;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/canvas/Float32Array.idl b/Source/core/html/canvas/Float32Array.idl
deleted file mode 100644
index 09e368b..0000000
--- a/Source/core/html/canvas/Float32Array.idl
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2006, 2010 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    GlobalContext=Window&WorkerGlobalScope,
-    ConstructorTemplate=TypedArray,
-    CustomToV8,
-    DoNotCheckConstants
-] interface Float32Array : ArrayBufferView {
-    const unsigned long BYTES_PER_ELEMENT = 4;
-
-    readonly attribute unsigned long length;
-    Float32Array subarray([Default=Undefined] optional long start,
-                          optional long end);
-
-    // void set(Float32Array array, optional in unsigned long offset);
-    // void set(sequence<long> array, optional in unsigned long offset);
-    void set();
-};
diff --git a/Source/core/html/canvas/Float64Array.idl b/Source/core/html/canvas/Float64Array.idl
deleted file mode 100644
index f9335ff..0000000
--- a/Source/core/html/canvas/Float64Array.idl
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    GlobalContext=Window&WorkerGlobalScope,
-    ConstructorTemplate=TypedArray,
-    CustomToV8,
-    DoNotCheckConstants
-] interface Float64Array : ArrayBufferView {
-    const unsigned long BYTES_PER_ELEMENT = 8;
-
-    readonly attribute unsigned long length;
-    Float64Array subarray([Default=Undefined] optional long start,
-                          optional long end);
-
-    // void set(Float64Array array, optional in unsigned long offset);
-    // void set(sequence<long> array, optional in unsigned long offset);
-    void set();
-};
diff --git a/Source/core/html/canvas/Int32Array.idl b/Source/core/html/canvas/Int32Array.idl
deleted file mode 100644
index 7b28526..0000000
--- a/Source/core/html/canvas/Int32Array.idl
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    GlobalContext=Window&WorkerGlobalScope,
-    ConstructorTemplate=TypedArray,
-    CustomToV8,
-    DoNotCheckConstants
-] interface Int32Array : ArrayBufferView {
-    const unsigned long BYTES_PER_ELEMENT = 4;
-
-    readonly attribute unsigned long length;
-    Int32Array subarray([Default=Undefined] optional long start,
-                        optional long end);
-
-    // void set(Int32Array array, optional in unsigned long offset);
-    // void set(sequence<long> array, optional in unsigned long offset);
-    void set();
-};
diff --git a/Source/core/html/canvas/Int8Array.idl b/Source/core/html/canvas/Int8Array.idl
deleted file mode 100644
index 0cd83d5..0000000
--- a/Source/core/html/canvas/Int8Array.idl
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    GlobalContext=Window&WorkerGlobalScope,
-    ConstructorTemplate=TypedArray,
-    CustomToV8,
-    DoNotCheckConstants
-] interface Int8Array : ArrayBufferView {
-    const unsigned long BYTES_PER_ELEMENT = 1;
-
-    readonly attribute unsigned long length;
-    Int8Array subarray([Default=Undefined] optional long start,
-                       optional long end);
-
-    // void set(Int8Array array, optional in unsigned long offset);
-    // void set(sequence<long> array, optional in unsigned long offset);
-    void set();
-};
diff --git a/Source/core/html/canvas/Uint16Array.idl b/Source/core/html/canvas/Uint16Array.idl
deleted file mode 100644
index dd62b02..0000000
--- a/Source/core/html/canvas/Uint16Array.idl
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    GlobalContext=Window&WorkerGlobalScope,
-    ConstructorTemplate=TypedArray,
-    CustomToV8,
-    DoNotCheckConstants
-] interface Uint16Array : ArrayBufferView {
-    const unsigned long BYTES_PER_ELEMENT = 2;
-
-    readonly attribute unsigned long length;
-    Uint16Array subarray([Default=Undefined] optional long start, optional long end);
-
-    // void set(Uint16Array array, optional in unsigned long offset);
-    // void set(sequence<long> array, optional in unsigned long offset);
-    void set();
-};
diff --git a/Source/core/html/canvas/Uint32Array.idl b/Source/core/html/canvas/Uint32Array.idl
deleted file mode 100644
index d47c7ca..0000000
--- a/Source/core/html/canvas/Uint32Array.idl
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    GlobalContext=Window&WorkerGlobalScope,
-    ConstructorTemplate=TypedArray,
-    CustomToV8,
-    DoNotCheckConstants
-] interface Uint32Array : ArrayBufferView {
-    const unsigned long BYTES_PER_ELEMENT = 4;
-
-    readonly attribute unsigned long length;
-    Uint32Array subarray([Default=Undefined] optional long start, optional long end);
-
-    // void set(Uint32Array array, optional in unsigned long offset);
-    // void set(sequence<long> array, optional in unsigned long offset);
-    void set();
-};
diff --git a/Source/core/html/canvas/Uint8Array.idl b/Source/core/html/canvas/Uint8Array.idl
deleted file mode 100644
index 6058506..0000000
--- a/Source/core/html/canvas/Uint8Array.idl
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    GlobalContext=Window&WorkerGlobalScope,
-    ConstructorTemplate=TypedArray,
-    CustomToV8,
-    DoNotCheckConstants
-] interface Uint8Array : ArrayBufferView {
-    const unsigned long BYTES_PER_ELEMENT = 1;
-
-    readonly attribute unsigned long length;
-    Uint8Array subarray([Default=Undefined] optional long start, optional long end);
-
-    // void set(Uint8Array array, optional in unsigned long offset);
-    // void set(sequence<long> array, optional in unsigned long offset);
-    void set();
-};
diff --git a/Source/core/html/canvas/Uint8ClampedArray.idl b/Source/core/html/canvas/Uint8ClampedArray.idl
deleted file mode 100644
index 66c9289..0000000
--- a/Source/core/html/canvas/Uint8ClampedArray.idl
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    GlobalContext=Window&WorkerGlobalScope,
-    ConstructorTemplate=TypedArray,
-    CustomToV8,
-    DoNotCheckConstants
-] interface Uint8ClampedArray : Uint8Array {
-    const unsigned long BYTES_PER_ELEMENT = 1;
-
-    readonly attribute unsigned long length;
-    Uint8ClampedArray subarray([Default=Undefined] optional long start, optional long end);
-
-    // FIXME: Missing other setters!
-    // void set(Uint8ClampedArray array, optional in unsigned long offset);
-    // void set(sequence<long> array, optional in unsigned long offset);
-    void set();
-};
diff --git a/Source/core/html/canvas/WebGLFramebuffer.cpp b/Source/core/html/canvas/WebGLFramebuffer.cpp
index 7f74aa7..ea0352a 100644
--- a/Source/core/html/canvas/WebGLFramebuffer.cpp
+++ b/Source/core/html/canvas/WebGLFramebuffer.cpp
@@ -28,6 +28,7 @@
 #include "core/html/canvas/WebGLFramebuffer.h"
 
 #include "core/html/canvas/WebGLRenderingContext.h"
+#include "core/platform/NotImplemented.h"
 #include "core/platform/graphics/Extensions3D.h"
 
 namespace WebCore {
@@ -48,6 +49,7 @@
         virtual GC3Dsizei getWidth() const;
         virtual GC3Dsizei getHeight() const;
         virtual GC3Denum getFormat() const;
+        virtual GC3Denum getType() const;
         virtual WebGLSharedObject* getObject() const;
         virtual bool isSharedObject(WebGLSharedObject*) const;
         virtual bool isValid() const;
@@ -144,6 +146,12 @@
             context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, attachment, GraphicsContext3D::RENDERBUFFER, 0);
     }
 
+    GC3Denum WebGLRenderbufferAttachment::getType() const
+    {
+        notImplemented();
+        return 0;
+    }
+
     class WebGLTextureAttachment : public WebGLFramebuffer::WebGLAttachment {
     public:
         static PassRefPtr<WebGLFramebuffer::WebGLAttachment> create(WebGLTexture*, GC3Denum target, GC3Dint level);
@@ -153,6 +161,7 @@
         virtual GC3Dsizei getWidth() const;
         virtual GC3Dsizei getHeight() const;
         virtual GC3Denum getFormat() const;
+        virtual GC3Denum getType() const;
         virtual WebGLSharedObject* getObject() const;
         virtual bool isSharedObject(WebGLSharedObject*) const;
         virtual bool isValid() const;
@@ -242,28 +251,21 @@
             context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, attachment, m_target, 0, m_level);
     }
 
-    bool isAttachmentComplete(WebGLFramebuffer::WebGLAttachment* attachedObject, GC3Denum attachment, const char** reason)
+    GC3Denum WebGLTextureAttachment::getType() const
     {
-        ASSERT(attachedObject && attachedObject->isValid());
-        ASSERT(reason);
-        GC3Denum format = attachedObject->getFormat();
-        unsigned need = GraphicsContext3D::getClearBitsByAttachmentType(attachment);
-        unsigned have = GraphicsContext3D::getClearBitsByFormat(format);
+        return m_texture->getType(m_target, m_level);
+    }
 
-        if ((need & have) != need) {
-            *reason = "attachment type is not correct for attachment";
+    bool isColorRenderable(GC3Denum internalformat)
+    {
+        switch (internalformat) {
+        case GraphicsContext3D::RGBA4:
+        case GraphicsContext3D::RGB5_A1:
+        case GraphicsContext3D::RGB565:
+            return true;
+        default:
             return false;
         }
-        if (!attachedObject->getWidth() || !attachedObject->getHeight()) {
-            *reason = "attachment has a 0 dimension";
-            return false;
-        }
-        if ((attachment == GraphicsContext3D::DEPTH_ATTACHMENT || attachment == GraphicsContext3D::STENCIL_ATTACHMENT)
-            && format == GraphicsContext3D::DEPTH_STENCIL) {
-          *reason = "attachment DEPTH_STENCIL not allowed on DEPTH or STENCIL attachment";
-          return false;
-        }
-        return true;
     }
 
 } // anonymous namespace
@@ -336,6 +338,92 @@
     return attachmentObject ? attachmentObject->getObject() : 0;
 }
 
+bool WebGLFramebuffer::isAttachmentComplete(WebGLAttachment* attachedObject, GC3Denum attachment, const char** reason) const
+{
+    ASSERT(attachedObject && attachedObject->isValid());
+    ASSERT(reason);
+
+    GC3Denum internalformat = attachedObject->getFormat();
+    WebGLSharedObject* object = attachedObject->getObject();
+    ASSERT(object && (object->isTexture() || object->isRenderbuffer()));
+
+    if (attachment == GraphicsContext3D::DEPTH_ATTACHMENT) {
+        if (object->isRenderbuffer()) {
+            if (internalformat != GraphicsContext3D::DEPTH_COMPONENT16) {
+                *reason = "the internalformat of the attached renderbuffer is not DEPTH_COMPONENT16";
+                return false;
+            }
+        } else if (object->isTexture()) {
+            GC3Denum type = attachedObject->getType();
+            if (!(context()->m_webglDepthTexture && internalformat == GraphicsContext3D::DEPTH_COMPONENT
+                && (type == GraphicsContext3D::UNSIGNED_SHORT || type == GraphicsContext3D::UNSIGNED_INT))) {
+                *reason = "the attached texture is not a depth texture";
+                return false;
+            }
+        }
+    } else if (attachment == GraphicsContext3D::STENCIL_ATTACHMENT) {
+        // Depend on the underlying GL drivers to check stencil textures
+        // and check renderbuffer type here only.
+        if (object->isRenderbuffer()) {
+            if (internalformat != GraphicsContext3D::STENCIL_INDEX8) {
+                *reason = "the internalformat of the attached renderbuffer is not STENCIL_INDEX8";
+                return false;
+            }
+        }
+    } else if (attachment == GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT) {
+        if (object->isRenderbuffer()) {
+            if (internalformat != GraphicsContext3D::DEPTH_STENCIL) {
+                *reason = "the internalformat of the attached renderbuffer is not DEPTH_STENCIL";
+                return false;
+            }
+        } else if (object->isTexture()) {
+            GC3Denum type = attachedObject->getType();
+            if (!(context()->m_webglDepthTexture && internalformat == GraphicsContext3D::DEPTH_STENCIL
+                && type == GraphicsContext3D::UNSIGNED_INT_24_8)) {
+                *reason = "the attached texture is not a DEPTH_STENCIL texture";
+                return false;
+            }
+        }
+    } else if (attachment == GraphicsContext3D::COLOR_ATTACHMENT0
+        || (context()->m_webglDrawBuffers && attachment > GraphicsContext3D::COLOR_ATTACHMENT0
+            && attachment < static_cast<GC3Denum>(GraphicsContext3D::COLOR_ATTACHMENT0 + context()->getMaxColorAttachments()))) {
+        if (object->isRenderbuffer()) {
+            if (!isColorRenderable(internalformat)) {
+                *reason = "the internalformat of the attached renderbuffer is not color-renderable";
+                return false;
+            }
+        } else if (object->isTexture()) {
+            GC3Denum type = attachedObject->getType();
+            if (internalformat != GraphicsContext3D::RGBA && internalformat != GraphicsContext3D::RGB) {
+                *reason = "the internalformat of the attached texture is not color-renderable";
+                return false;
+            }
+            // TODO: WEBGL_color_buffer_float and EXT_color_buffer_half_float extensions have not been implemented in
+            // WebGL yet. It would be better to depend on the underlying GL drivers to check on rendering to floating point textures
+            // and add the check back to WebGL when above two extensions are implemented.
+            // Assume UNSIGNED_BYTE is renderable here without the need to explicitly check if GL_OES_rgb8_rgba8 extension is supported.
+            if (type != GraphicsContext3D::UNSIGNED_BYTE
+                && type != GraphicsContext3D::UNSIGNED_SHORT_5_6_5
+                && type != GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4
+                && type != GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1
+                && !(type == GraphicsContext3D::FLOAT && context()->m_oesTextureFloat)
+                && !(type == GraphicsContext3D::HALF_FLOAT_OES && context()->m_oesTextureHalfFloat)) {
+                *reason = "unsupported type: The attached texture is not supported to be rendered to";
+                return false;
+            }
+        }
+    } else {
+        *reason = "unknown framebuffer attachment point";
+        return false;
+    }
+
+    if (!attachedObject->getWidth() || !attachedObject->getHeight()) {
+        *reason = "attachment has a 0 dimension";
+        return false;
+    }
+    return true;
+}
+
 WebGLFramebuffer::WebGLAttachment* WebGLFramebuffer::getAttachment(GC3Denum attachment) const
 {
     const AttachmentMap::const_iterator it = m_attachments.find(attachment);
diff --git a/Source/core/html/canvas/WebGLFramebuffer.h b/Source/core/html/canvas/WebGLFramebuffer.h
index ff40734..7b6edba 100644
--- a/Source/core/html/canvas/WebGLFramebuffer.h
+++ b/Source/core/html/canvas/WebGLFramebuffer.h
@@ -46,6 +46,11 @@
         virtual GC3Dsizei getWidth() const = 0;
         virtual GC3Dsizei getHeight() const = 0;
         virtual GC3Denum getFormat() const = 0;
+        // For texture attachment, getType() returns the type of the attached texture.
+        // For renderbuffer attachment, the type of the renderbuffer may vary with GL implementation.
+        // To avoid confusion, it would be better to not implement getType() for renderbuffer attachment and
+        // we should always use the internalformat of the renderbuffer and avoid using getType() API.
+        virtual GC3Denum getType() const = 0;
         virtual WebGLSharedObject* getObject() const = 0;
         virtual bool isSharedObject(WebGLSharedObject*) const = 0;
         virtual bool isValid() const = 0;
@@ -109,6 +114,7 @@
     virtual bool isFramebuffer() const { return true; }
 
     WebGLAttachment* getAttachment(GC3Denum) const;
+    bool isAttachmentComplete(WebGLAttachment* attachedObject, GC3Denum attachment, const char** reason) const;
 
     // Check if the framebuffer is currently bound.
     bool isBound() const;
diff --git a/Source/core/html/canvas/WebGLRenderingContext.cpp b/Source/core/html/canvas/WebGLRenderingContext.cpp
index 91b3dfc..01e667d 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -66,7 +66,7 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
diff --git a/Source/core/html/ime/InputMethodContext.cpp b/Source/core/html/ime/InputMethodContext.cpp
index 3f59140..3518a7b 100644
--- a/Source/core/html/ime/InputMethodContext.cpp
+++ b/Source/core/html/ime/InputMethodContext.cpp
@@ -31,11 +31,9 @@
 #include "config.h"
 #include "core/html/ime/InputMethodContext.h"
 
-#include "core/editing/Editor.h"
+#include "core/editing/InputMethodController.h"
 #include "core/html/ime/Composition.h"
-#include "core/page/EditorClient.h"
 #include "core/page/Frame.h"
-#include "core/page/Page.h"
 
 namespace WebCore {
 
@@ -78,27 +76,12 @@
     Frame* frame = m_element->document()->frame();
     if (!frame)
         return;
-    Editor* editor = frame->editor();
-    if (!editor->hasComposition())
-        return;
 
     const Element* element = frame->document()->focusedElement();
     if (!element || !element->isHTMLElement() || m_element != toHTMLElement(element))
         return;
 
-    // We should verify the parent node of this IME composition node are
-    // editable because JavaScript may delete a parent node of the composition
-    // node. In this case, WebKit crashes while deleting texts from the parent
-    // node, which doesn't exist any longer.
-    RefPtr<Range> range = editor->compositionRange();
-    if (range) {
-        Node* node = range->startContainer();
-        if (!node || !node->isContentEditable())
-            return;
-    }
-
-    // This resets input method and the composition string is committed.
-    editor->client()->willSetInputMethodState();
+    frame->inputMethodController().confirmCompositionAndResetState();
 }
 
 void InputMethodContext::setCaretRectangle(Node* anchor, int x, int y, int w, int h)
diff --git a/Source/core/html/parser/CSSPreloadScanner.cpp b/Source/core/html/parser/CSSPreloadScanner.cpp
index bd1f1af..10ab28d 100644
--- a/Source/core/html/parser/CSSPreloadScanner.cpp
+++ b/Source/core/html/parser/CSSPreloadScanner.cpp
@@ -28,6 +28,7 @@
 #include "config.h"
 #include "core/html/parser/CSSPreloadScanner.h"
 
+#include "FetchInitiatorTypeNames.h"
 #include "core/html/parser/HTMLIdentifier.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/platform/text/SegmentedString.h"
@@ -216,7 +217,7 @@
         if (!url.isEmpty()) {
             KURL baseElementURL; // FIXME: This should be passed in from the HTMLPreloadScaner via scan()!
             TextPosition position = TextPosition(source.currentLine(), source.currentColumn());
-            OwnPtr<PreloadRequest> request = PreloadRequest::create("css", position, url, baseElementURL, Resource::CSSStyleSheet);
+            OwnPtr<PreloadRequest> request = PreloadRequest::create(FetchInitiatorTypeNames::css, position, url, baseElementURL, Resource::CSSStyleSheet);
             // FIXME: Should this be including the charset in the preload request?
             m_requests->append(request.release());
         }
diff --git a/Source/core/html/parser/HTMLDocumentParser.cpp b/Source/core/html/parser/HTMLDocumentParser.cpp
index 1719851..cdc7e0a 100644
--- a/Source/core/html/parser/HTMLDocumentParser.cpp
+++ b/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -41,6 +41,7 @@
 #include "core/html/parser/HTMLTreeBuilder.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Frame.h"
+#include "core/platform/chromium/TraceEvent.h"
 #include "wtf/Functional.h"
 
 namespace WebCore {
@@ -683,10 +684,11 @@
             startBackgroundParser();
 
         ASSERT(inputSource->hasOneRef());
-        Closure closure = bind(&BackgroundHTMLParser::append, m_backgroundParser, String(inputSource));
+        TRACE_EVENT1("net", "HTMLDocumentParser::append", "size", inputSource->length());
         // NOTE: Important that the String temporary is destroyed before we post the task
         // otherwise the String could call deref() on a StringImpl now owned by the background parser.
         // We would like to ASSERT(closure.arg3()->hasOneRef()) but sadly the args are private.
+        Closure closure = bind(&BackgroundHTMLParser::append, m_backgroundParser, String(inputSource));
         HTMLParserThread::shared()->postTask(closure);
         return;
     }
@@ -694,6 +696,7 @@
     // pumpTokenizer can cause this parser to be detached from the Document,
     // but we need to ensure it isn't deleted yet.
     RefPtr<HTMLDocumentParser> protect(this);
+    TRACE_EVENT1("net", "HTMLDocumentParser::append", "size", inputSource->length());
     String source(inputSource);
 
     if (m_preloadScanner) {
@@ -875,18 +878,18 @@
     endIfDelayed();
 }
 
-void HTMLDocumentParser::watchForLoad(Resource* cachedScript)
+void HTMLDocumentParser::watchForLoad(Resource* resource)
 {
-    ASSERT(!cachedScript->isLoaded());
+    ASSERT(!resource->isLoaded());
     // addClient would call notifyFinished if the load were complete.
     // Callers do not expect to be re-entered from this call, so they should
     // not an already-loaded Resource.
-    cachedScript->addClient(this);
+    resource->addClient(this);
 }
 
-void HTMLDocumentParser::stopWatchingForLoad(Resource* cachedScript)
+void HTMLDocumentParser::stopWatchingForLoad(Resource* resource)
 {
-    cachedScript->removeClient(this);
+    resource->removeClient(this);
 }
 
 void HTMLDocumentParser::appendCurrentInputStreamToPreloadScannerAndScan()
diff --git a/Source/core/html/parser/HTMLEntityParser.cpp b/Source/core/html/parser/HTMLEntityParser.cpp
index f0d78ef..97cebee 100644
--- a/Source/core/html/parser/HTMLEntityParser.cpp
+++ b/Source/core/html/parser/HTMLEntityParser.cpp
@@ -30,7 +30,6 @@
 
 #include "core/html/parser/HTMLEntitySearch.h"
 #include "core/html/parser/HTMLEntityTable.h"
-#include "core/xml/parser/CharacterReferenceParserInlines.h"
 #include "wtf/text/StringBuilder.h"
 
 using namespace WTF;
@@ -44,88 +43,230 @@
     0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, // 98-9F
 };
 
-static inline bool isAlphaNumeric(UChar cc)
+static bool isAlphaNumeric(UChar cc)
 {
     return (cc >= '0' && cc <= '9') || (cc >= 'a' && cc <= 'z') || (cc >= 'A' && cc <= 'Z');
 }
 
-class HTMLEntityParser {
-public:
-    inline static UChar adjustEntity(UChar32 value)
-    {
-        if ((value & ~0x1F) != 0x0080)
-            return value;
-        return windowsLatin1ExtensionArray[value - 0x80];
-    }
-
-    inline static UChar32 legalEntityFor(UChar32 value)
-    {
-        // FIXME: A number of specific entity values generate parse errors.
-        if (value <= 0 || value > 0x10FFFF || (value >= 0xD800 && value <= 0xDFFF))
-            return 0xFFFD;
-        if (U_IS_BMP(value))
-            return adjustEntity(value);
+static UChar adjustEntity(UChar32 value)
+{
+    if ((value & ~0x1F) != 0x0080)
         return value;
+    return windowsLatin1ExtensionArray[value - 0x80];
+}
+
+static void appendLegalEntityFor(UChar32 c, DecodedHTMLEntity& decodedEntity)
+{
+    // FIXME: A number of specific entity values generate parse errors.
+    if (c <= 0 || c > 0x10FFFF || (c >= 0xD800 && c <= 0xDFFF)) {
+        decodedEntity.append(0xFFFD);
+        return;
     }
+    if (U_IS_BMP(c)) {
+        decodedEntity.append(adjustEntity(c));
+        return;
+    }
+    decodedEntity.append(c);
+}
 
-    inline static bool acceptMalformed() { return true; }
+static const UChar32 kInvalidUnicode = -1;
 
-    inline static bool consumeNamedEntity(SegmentedString& source, StringBuilder& decodedEntity, bool& notEnoughCharacters, UChar additionalAllowedCharacter, UChar& cc)
-    {
-        StringBuilder consumedCharacters;
-        HTMLEntitySearch entitySearch;
-        while (!source.isEmpty()) {
-            cc = source.currentChar();
-            entitySearch.advance(cc);
-            if (!entitySearch.isEntityPrefix())
-                break;
-            consumedCharacters.append(cc);
-            source.advanceAndASSERT(cc);
-        }
-        notEnoughCharacters = source.isEmpty();
-        if (notEnoughCharacters) {
-            // We can't an entity because there might be a longer entity
-            // that we could match if we had more data.
-            unconsumeCharacters(source, consumedCharacters);
-            return false;
-        }
-        if (!entitySearch.mostRecentMatch()) {
-            unconsumeCharacters(source, consumedCharacters);
-            return false;
-        }
-        if (entitySearch.mostRecentMatch()->length != entitySearch.currentLength()) {
-            // We've consumed too many characters. We need to walk the
-            // source back to the point at which we had consumed an
-            // actual entity.
-            unconsumeCharacters(source, consumedCharacters);
-            consumedCharacters.clear();
-            const int length = entitySearch.mostRecentMatch()->length;
-            const UChar* reference = entitySearch.mostRecentMatch()->entity;
-            for (int i = 0; i < length; ++i) {
-                cc = source.currentChar();
-                ASSERT_UNUSED(reference, cc == *reference++);
-                consumedCharacters.append(cc);
-                source.advanceAndASSERT(cc);
-                ASSERT(!source.isEmpty());
-            }
-            cc = source.currentChar();
-        }
-        if (entitySearch.mostRecentMatch()->lastCharacter() == ';'
-            || !additionalAllowedCharacter
-            || !(isAlphaNumeric(cc) || cc == '=')) {
-            decodedEntity.append(entitySearch.mostRecentMatch()->firstValue);
-            if (entitySearch.mostRecentMatch()->secondValue)
-                decodedEntity.append(entitySearch.mostRecentMatch()->secondValue);
-            return true;
-        }
+static bool isHexDigit(UChar cc)
+{
+    return (cc >= '0' && cc <= '9') || (cc >= 'a' && cc <= 'f') || (cc >= 'A' && cc <= 'F');
+}
+
+static UChar asHexDigit(UChar cc)
+{
+    if (cc >= '0' && cc <= '9')
+      return cc - '0';
+    if (cc >= 'a' && cc <= 'z')
+      return 10 + cc - 'a';
+    if (cc >= 'A' && cc <= 'Z')
+      return 10 + cc - 'A';
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
+typedef Vector<UChar, 64> ConsumedCharacterBuffer;
+
+static void unconsumeCharacters(SegmentedString& source, ConsumedCharacterBuffer& consumedCharacters)
+{
+    if (consumedCharacters.size() == 1)
+        source.push(consumedCharacters[0]);
+    else if (consumedCharacters.size() == 2) {
+        source.push(consumedCharacters[0]);
+        source.push(consumedCharacters[1]);
+    } else
+        source.prepend(SegmentedString(String(consumedCharacters)));
+}
+
+static bool consumeNamedEntity(SegmentedString& source, DecodedHTMLEntity& decodedEntity, bool& notEnoughCharacters, UChar additionalAllowedCharacter, UChar& cc)
+{
+    ConsumedCharacterBuffer consumedCharacters;
+    HTMLEntitySearch entitySearch;
+    while (!source.isEmpty()) {
+        cc = source.currentChar();
+        entitySearch.advance(cc);
+        if (!entitySearch.isEntityPrefix())
+            break;
+        consumedCharacters.append(cc);
+        source.advanceAndASSERT(cc);
+    }
+    notEnoughCharacters = source.isEmpty();
+    if (notEnoughCharacters) {
+        // We can't an entity because there might be a longer entity
+        // that we could match if we had more data.
         unconsumeCharacters(source, consumedCharacters);
         return false;
     }
-};
+    if (!entitySearch.mostRecentMatch()) {
+        unconsumeCharacters(source, consumedCharacters);
+        return false;
+    }
+    if (entitySearch.mostRecentMatch()->length != entitySearch.currentLength()) {
+        // We've consumed too many characters. We need to walk the
+        // source back to the point at which we had consumed an
+        // actual entity.
+        unconsumeCharacters(source, consumedCharacters);
+        consumedCharacters.clear();
+        const int length = entitySearch.mostRecentMatch()->length;
+        const UChar* reference = entitySearch.mostRecentMatch()->entity;
+        for (int i = 0; i < length; ++i) {
+            cc = source.currentChar();
+            ASSERT_UNUSED(reference, cc == *reference++);
+            consumedCharacters.append(cc);
+            source.advanceAndASSERT(cc);
+            ASSERT(!source.isEmpty());
+        }
+        cc = source.currentChar();
+    }
+    if (entitySearch.mostRecentMatch()->lastCharacter() == ';'
+        || !additionalAllowedCharacter
+        || !(isAlphaNumeric(cc) || cc == '=')) {
+        decodedEntity.append(entitySearch.mostRecentMatch()->firstValue);
+        if (UChar32 second = entitySearch.mostRecentMatch()->secondValue)
+            decodedEntity.append(second);
+        return true;
+    }
+    unconsumeCharacters(source, consumedCharacters);
+    return false;
+}
 
-bool consumeHTMLEntity(SegmentedString& source, StringBuilder& decodedEntity, bool& notEnoughCharacters, UChar additionalAllowedCharacter)
+bool consumeHTMLEntity(SegmentedString& source, DecodedHTMLEntity& decodedEntity, bool& notEnoughCharacters, UChar additionalAllowedCharacter)
 {
-    return consumeCharacterReference<HTMLEntityParser>(source, decodedEntity, notEnoughCharacters, additionalAllowedCharacter);
+    ASSERT(!additionalAllowedCharacter || additionalAllowedCharacter == '"' || additionalAllowedCharacter == '\'' || additionalAllowedCharacter == '>');
+    ASSERT(!notEnoughCharacters);
+    ASSERT(decodedEntity.isEmpty());
+
+    enum EntityState {
+        Initial,
+        Number,
+        MaybeHexLowerCaseX,
+        MaybeHexUpperCaseX,
+        Hex,
+        Decimal,
+        Named
+    };
+    EntityState entityState = Initial;
+    UChar32 result = 0;
+    ConsumedCharacterBuffer consumedCharacters;
+
+    while (!source.isEmpty()) {
+        UChar cc = source.currentChar();
+        switch (entityState) {
+        case Initial: {
+            if (cc == '\x09' || cc == '\x0A' || cc == '\x0C' || cc == ' ' || cc == '<' || cc == '&')
+                return false;
+            if (additionalAllowedCharacter && cc == additionalAllowedCharacter)
+                return false;
+            if (cc == '#') {
+                entityState = Number;
+                break;
+            }
+            if ((cc >= 'a' && cc <= 'z') || (cc >= 'A' && cc <= 'Z')) {
+                entityState = Named;
+                continue;
+            }
+            return false;
+        }
+        case Number: {
+            if (cc == 'x') {
+                entityState = MaybeHexLowerCaseX;
+                break;
+            }
+            if (cc == 'X') {
+                entityState = MaybeHexUpperCaseX;
+                break;
+            }
+            if (cc >= '0' && cc <= '9') {
+                entityState = Decimal;
+                continue;
+            }
+            source.push('#');
+            return false;
+        }
+        case MaybeHexLowerCaseX: {
+            if (isHexDigit(cc)) {
+                entityState = Hex;
+                continue;
+            }
+            source.push('#');
+            source.push('x');
+            return false;
+        }
+        case MaybeHexUpperCaseX: {
+            if (isHexDigit(cc)) {
+                entityState = Hex;
+                continue;
+            }
+            source.push('#');
+            source.push('X');
+            return false;
+        }
+        case Hex: {
+            if (isHexDigit(cc)) {
+                if (result != kInvalidUnicode)
+                    result = result * 16 + asHexDigit(cc);
+            } else if (cc == ';') {
+                source.advanceAndASSERT(cc);
+                appendLegalEntityFor(result, decodedEntity);
+                return true;
+            } else {
+                appendLegalEntityFor(result, decodedEntity);
+                return true;
+            }
+            break;
+        }
+        case Decimal: {
+            if (cc >= '0' && cc <= '9') {
+                if (result != kInvalidUnicode)
+                    result = result * 10 + cc - '0';
+            } else if (cc == ';') {
+                source.advanceAndASSERT(cc);
+                appendLegalEntityFor(result, decodedEntity);
+                return true;
+            } else {
+                appendLegalEntityFor(result, decodedEntity);
+                return true;
+            }
+            break;
+        }
+        case Named: {
+            return consumeNamedEntity(source, decodedEntity, notEnoughCharacters, additionalAllowedCharacter, cc);
+        }
+        }
+
+        if (result > UCHAR_MAX_VALUE)
+            result = kInvalidUnicode;
+
+        consumedCharacters.append(cc);
+        source.advanceAndASSERT(cc);
+    }
+    ASSERT(source.isEmpty());
+    notEnoughCharacters = true;
+    unconsumeCharacters(source, consumedCharacters);
+    return false;
 }
 
 static size_t appendUChar32ToUCharArray(UChar32 value, UChar* result)
diff --git a/Source/core/html/parser/HTMLEntityParser.h b/Source/core/html/parser/HTMLEntityParser.h
index fc12f62..12499c7 100644
--- a/Source/core/html/parser/HTMLEntityParser.h
+++ b/Source/core/html/parser/HTMLEntityParser.h
@@ -31,7 +31,37 @@
 
 namespace WebCore {
 
-bool consumeHTMLEntity(SegmentedString&, StringBuilder& decodedEntity, bool& notEnoughCharacters, UChar additionalAllowedCharacter = '\0');
+class DecodedHTMLEntity {
+private:
+    // HTML entities contain at most four UTF-16 code units.
+    static const unsigned kMaxLength = 4;
+
+public:
+    DecodedHTMLEntity() : length(0) { }
+
+    bool isEmpty() const { return !length; }
+
+    void append(UChar c)
+    {
+        RELEASE_ASSERT(length < kMaxLength);
+        data[length++] = c;
+    }
+
+    void append(UChar32 c)
+    {
+        if (U_IS_BMP(c)) {
+            append(static_cast<UChar>(c));
+            return;
+        }
+        append(U16_LEAD(c));
+        append(U16_TRAIL(c));
+    }
+
+    unsigned length;
+    UChar data[kMaxLength];
+};
+
+bool consumeHTMLEntity(SegmentedString&, DecodedHTMLEntity& decodedEntity, bool& notEnoughCharacters, UChar additionalAllowedCharacter = '\0');
 
 // Used by the XML parser.  Not suitable for use in HTML parsing.  Use consumeHTMLEntity instead.
 size_t decodeNamedEntityToUCharArray(const char*, UChar result[4]);
diff --git a/Source/core/html/parser/HTMLPreloadScanner.cpp b/Source/core/html/parser/HTMLPreloadScanner.cpp
index 306fc7c..0b51791 100644
--- a/Source/core/html/parser/HTMLPreloadScanner.cpp
+++ b/Source/core/html/parser/HTMLPreloadScanner.cpp
@@ -33,6 +33,7 @@
 #include "core/html/LinkRelAttribute.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/HTMLTokenizer.h"
+#include "core/platform/chromium/TraceEvent.h"
 #include "wtf/MainThread.h"
 
 namespace WebCore {
@@ -84,7 +85,7 @@
     if (match(tagImpl, scriptTag))
         return scriptTag.localName();
     ASSERT_NOT_REACHED();
-    return "unknown";
+    return emptyString();
 }
 
 class TokenPreloadScanner::StartTagScanner {
@@ -126,6 +127,7 @@
         if (!shouldPreload())
             return nullptr;
 
+        TRACE_EVENT_INSTANT1("net", "PreloadRequest", "url", m_urlToLoad.ascii());
         TextPosition position = TextPosition(source.currentLine(), source.currentColumn());
         OwnPtr<PreloadRequest> request = PreloadRequest::create(initiatorFor(m_tagImpl), position, m_urlToLoad, predictedBaseURL, resourceType(), m_mediaAttribute);
         request->setCrossOriginModeAllowsCookies(crossOriginModeAllowsCookies());
@@ -188,11 +190,11 @@
         if (match(m_tagImpl, scriptTag))
             return Resource::Script;
         if (match(m_tagImpl, imgTag) || (match(m_tagImpl, inputTag) && m_inputIsImage))
-            return Resource::ImageResource;
+            return Resource::Image;
         if (match(m_tagImpl, linkTag) && m_linkIsStyleSheet)
             return Resource::CSSStyleSheet;
         ASSERT_NOT_REACHED();
-        return Resource::RawResource;
+        return Resource::Raw;
     }
 
     bool shouldPreload()
diff --git a/Source/core/html/parser/HTMLResourcePreloader.cpp b/Source/core/html/parser/HTMLResourcePreloader.cpp
index 7c4f8b4..4960d81 100644
--- a/Source/core/html/parser/HTMLResourcePreloader.cpp
+++ b/Source/core/html/parser/HTMLResourcePreloader.cpp
@@ -32,6 +32,7 @@
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/css/MediaList.h"
 #include "core/css/MediaQueryEvaluator.h"
+#include "core/platform/HistogramSupport.h"
 #include "core/rendering/RenderObject.h"
 
 namespace WebCore {
@@ -92,6 +93,7 @@
         return;
 
     FetchRequest request = preload->resourceRequest(m_document);
+    HistogramSupport::histogramCustomCounts("WebCore.PreloadDelayMs", static_cast<int>(1000 * (monotonicallyIncreasingTime() - preload->discoveryTime())), 0, 2000, 20);
     loadingDocument->fetcher()->preload(preload->resourceType(), request, preload->charset());
 }
 
diff --git a/Source/core/html/parser/HTMLResourcePreloader.h b/Source/core/html/parser/HTMLResourcePreloader.h
index 89ecb92..1b94671 100644
--- a/Source/core/html/parser/HTMLResourcePreloader.h
+++ b/Source/core/html/parser/HTMLResourcePreloader.h
@@ -28,6 +28,7 @@
 
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/Resource.h"
+#include "wtf/CurrentTime.h"
 #include "wtf/text/TextPosition.h"
 
 namespace WebCore {
@@ -50,19 +51,21 @@
 
     const String& charset() const { return m_charset; }
     const String& media() const { return m_mediaAttribute; }
+    double discoveryTime() const { return m_discoveryTime; }
     void setCharset(const String& charset) { m_charset = charset.isolatedCopy(); }
     void setCrossOriginModeAllowsCookies(bool allowsCookies) { m_crossOriginModeAllowsCookies = allowsCookies; }
     Resource::Type resourceType() const { return m_resourceType; }
 
 private:
     PreloadRequest(const String& initiatorName, const TextPosition& initiatorPosition, const String& resourceURL, const KURL& baseURL, Resource::Type resourceType, const String& mediaAttribute)
-        : m_initiatorName(initiatorName.isolatedCopy())
+        : m_initiatorName(initiatorName)
         , m_initiatorPosition(initiatorPosition)
         , m_resourceURL(resourceURL.isolatedCopy())
         , m_baseURL(baseURL.copy())
         , m_resourceType(resourceType)
         , m_mediaAttribute(mediaAttribute.isolatedCopy())
         , m_crossOriginModeAllowsCookies(false)
+        , m_discoveryTime(monotonicallyIncreasingTime())
     {
     }
 
@@ -76,6 +79,7 @@
     Resource::Type m_resourceType;
     String m_mediaAttribute;
     bool m_crossOriginModeAllowsCookies;
+    double m_discoveryTime;
 };
 
 typedef Vector<OwnPtr<PreloadRequest> > PreloadRequestStream;
diff --git a/Source/core/html/parser/HTMLScriptRunner.cpp b/Source/core/html/parser/HTMLScriptRunner.cpp
index 4ee98da..5141c82 100644
--- a/Source/core/html/parser/HTMLScriptRunner.cpp
+++ b/Source/core/html/parser/HTMLScriptRunner.cpp
@@ -35,7 +35,7 @@
 #include "core/html/parser/HTMLInputStream.h"
 #include "core/html/parser/HTMLScriptRunnerHost.h"
 #include "core/html/parser/NestingLevelIncrementer.h"
-#include "core/loader/cache/CachedScript.h"
+#include "core/loader/cache/ScriptResource.h"
 #include "core/page/Frame.h"
 #include "core/platform/NotImplemented.h"
 
@@ -55,12 +55,12 @@
 HTMLScriptRunner::~HTMLScriptRunner()
 {
     // FIXME: Should we be passed a "done loading/parsing" callback sooner than destruction?
-    if (m_parserBlockingScript.cachedScript() && m_parserBlockingScript.watchingForLoad())
+    if (m_parserBlockingScript.resource() && m_parserBlockingScript.watchingForLoad())
         stopWatchingForLoad(m_parserBlockingScript);
 
     while (!m_scriptsToExecuteAfterParsing.isEmpty()) {
         PendingScript pendingScript = m_scriptsToExecuteAfterParsing.takeFirst();
-        if (pendingScript.cachedScript() && pendingScript.watchingForLoad())
+        if (pendingScript.resource() && pendingScript.watchingForLoad())
             stopWatchingForLoad(pendingScript);
     }
 }
@@ -86,10 +86,10 @@
 
 ScriptSourceCode HTMLScriptRunner::sourceFromPendingScript(const PendingScript& script, bool& errorOccurred) const
 {
-    if (script.cachedScript()) {
-        errorOccurred = script.cachedScript()->errorOccurred();
-        ASSERT(script.cachedScript()->isLoaded());
-        return ScriptSourceCode(script.cachedScript());
+    if (script.resource()) {
+        errorOccurred = script.resource()->errorOccurred();
+        ASSERT(script.resource()->isLoaded());
+        return ScriptSourceCode(script.resource());
     }
     errorOccurred = false;
     return ScriptSourceCode(script.element()->textContent(), documentURLForScriptExecution(m_document), script.startingPosition());
@@ -100,7 +100,7 @@
     m_hasScriptsWaitingForResources = !m_document->haveStylesheetsAndImportsLoaded();
     if (m_hasScriptsWaitingForResources)
         return false;
-    if (script.cachedScript() && !script.cachedScript()->isLoaded())
+    if (script.resource() && !script.resource()->isLoaded())
         return false;
     return true;
 }
@@ -122,7 +122,7 @@
     ScriptSourceCode sourceCode = sourceFromPendingScript(pendingScript, errorOccurred);
 
     // Stop watching loads before executeScript to prevent recursion if the script reloads itself.
-    if (pendingScript.cachedScript() && pendingScript.watchingForLoad())
+    if (pendingScript.resource() && pendingScript.watchingForLoad())
         stopWatchingForLoad(pendingScript);
 
     if (!isExecutingScript())
@@ -147,14 +147,14 @@
 void HTMLScriptRunner::watchForLoad(PendingScript& pendingScript)
 {
     ASSERT(!pendingScript.watchingForLoad());
-    m_host->watchForLoad(pendingScript.cachedScript());
+    m_host->watchForLoad(pendingScript.resource());
     pendingScript.setWatchingForLoad(true);
 }
 
 void HTMLScriptRunner::stopWatchingForLoad(PendingScript& pendingScript)
 {
     ASSERT(pendingScript.watchingForLoad());
-    m_host->stopWatchingForLoad(pendingScript.cachedScript());
+    m_host->stopWatchingForLoad(pendingScript.resource());
     pendingScript.setWatchingForLoad(false);
 }
 
@@ -191,12 +191,12 @@
         executeParsingBlockingScript();
 }
 
-void HTMLScriptRunner::executeScriptsWaitingForLoad(Resource* cachedScript)
+void HTMLScriptRunner::executeScriptsWaitingForLoad(Resource* resource)
 {
     ASSERT(!isExecutingScript());
     ASSERT(hasParserBlockingScript());
-    ASSERT_UNUSED(cachedScript, m_parserBlockingScript.cachedScript() == cachedScript);
-    ASSERT(m_parserBlockingScript.cachedScript()->isLoaded());
+    ASSERT_UNUSED(resource, m_parserBlockingScript.resource() == resource);
+    ASSERT(m_parserBlockingScript.resource()->isLoaded());
     executeParsingBlockingScripts();
 }
 
@@ -216,8 +216,8 @@
     while (!m_scriptsToExecuteAfterParsing.isEmpty()) {
         ASSERT(!isExecutingScript());
         ASSERT(!hasParserBlockingScript());
-        ASSERT(m_scriptsToExecuteAfterParsing.first().cachedScript());
-        if (!m_scriptsToExecuteAfterParsing.first().cachedScript()->isLoaded()) {
+        ASSERT(m_scriptsToExecuteAfterParsing.first().resource());
+        if (!m_scriptsToExecuteAfterParsing.first().resource()->isLoaded()) {
             watchForLoad(m_scriptsToExecuteAfterParsing.first());
             return false;
         }
@@ -235,12 +235,12 @@
     if (!requestPendingScript(m_parserBlockingScript, element))
         return;
 
-    ASSERT(m_parserBlockingScript.cachedScript());
+    ASSERT(m_parserBlockingScript.resource());
 
-    // We only care about a load callback if cachedScript is not already
+    // We only care about a load callback if resource is not already
     // in the cache. Callers will attempt to run the m_parserBlockingScript
     // if possible before returning control to the parser.
-    if (!m_parserBlockingScript.cachedScript()->isLoaded())
+    if (!m_parserBlockingScript.resource()->isLoaded())
         watchForLoad(m_parserBlockingScript);
 }
 
@@ -250,7 +250,7 @@
     if (!requestPendingScript(pendingScript, element))
         return;
 
-    ASSERT(pendingScript.cachedScript());
+    ASSERT(pendingScript.resource());
     m_scriptsToExecuteAfterParsing.append(pendingScript);
 }
 
@@ -259,12 +259,12 @@
     ASSERT(!pendingScript.element());
     pendingScript.setElement(script);
     // This should correctly return 0 for empty or invalid srcValues.
-    CachedScript* cachedScript = toScriptLoaderIfPossible(script)->cachedScript().get();
-    if (!cachedScript) {
+    ScriptResource* resource = toScriptLoaderIfPossible(script)->resource().get();
+    if (!resource) {
         notImplemented(); // Dispatch error event.
         return false;
     }
-    pendingScript.setCachedScript(cachedScript);
+    pendingScript.setScriptResource(resource);
     return true;
 }
 
diff --git a/Source/core/html/parser/HTMLScriptRunner.h b/Source/core/html/parser/HTMLScriptRunner.h
index 98d84c7..82d8bc2 100644
--- a/Source/core/html/parser/HTMLScriptRunner.h
+++ b/Source/core/html/parser/HTMLScriptRunner.h
@@ -34,7 +34,7 @@
 namespace WebCore {
 
 class Resource;
-class CachedScript;
+class ScriptResource;
 class Document;
 class Element;
 class Frame;
diff --git a/Source/core/html/parser/HTMLTokenizer.cpp b/Source/core/html/parser/HTMLTokenizer.cpp
index 0931934..c78cd59 100644
--- a/Source/core/html/parser/HTMLTokenizer.cpp
+++ b/Source/core/html/parser/HTMLTokenizer.cpp
@@ -155,7 +155,7 @@
 inline bool HTMLTokenizer::processEntity(SegmentedString& source)
 {
     bool notEnoughCharacters = false;
-    StringBuilder decodedEntity;
+    DecodedHTMLEntity decodedEntity;
     bool success = consumeHTMLEntity(source, decodedEntity, notEnoughCharacters);
     if (notEnoughCharacters)
         return false;
@@ -163,8 +163,8 @@
         ASSERT(decodedEntity.isEmpty());
         bufferCharacter('&');
     } else {
-        for (unsigned i = 0; i < decodedEntity.length(); ++i)
-            bufferCharacter(decodedEntity[i]);
+        for (unsigned i = 0; i < decodedEntity.length; ++i)
+            bufferCharacter(decodedEntity.data[i]);
     }
     return true;
 }
@@ -996,7 +996,7 @@
 
     HTML_BEGIN_STATE(CharacterReferenceInAttributeValueState) {
         bool notEnoughCharacters = false;
-        StringBuilder decodedEntity;
+        DecodedHTMLEntity decodedEntity;
         bool success = consumeHTMLEntity(source, decodedEntity, notEnoughCharacters, m_additionalAllowedCharacter);
         if (notEnoughCharacters)
             return haveBufferedCharacterToken();
@@ -1004,8 +1004,8 @@
             ASSERT(decodedEntity.isEmpty());
             m_token->appendToAttributeValue('&');
         } else {
-            for (unsigned i = 0; i < decodedEntity.length(); ++i)
-                m_token->appendToAttributeValue(decodedEntity[i]);
+            for (unsigned i = 0; i < decodedEntity.length; ++i)
+                m_token->appendToAttributeValue(decodedEntity.data[i]);
         }
         // We're supposed to switch back to the attribute value state that
         // we were in when we were switched into this state. Rather than
@@ -1072,9 +1072,9 @@
     END_STATE()
 
     HTML_BEGIN_STATE(MarkupDeclarationOpenState) {
-        DEFINE_STATIC_LOCAL(String, dashDashString, (ASCIILiteral("--")));
-        DEFINE_STATIC_LOCAL(String, doctypeString, (ASCIILiteral("doctype")));
-        DEFINE_STATIC_LOCAL(String, cdataString, (ASCIILiteral("[CDATA[")));
+        DEFINE_STATIC_LOCAL(String, dashDashString, ("--"));
+        DEFINE_STATIC_LOCAL(String, doctypeString, ("doctype"));
+        DEFINE_STATIC_LOCAL(String, cdataString, ("[CDATA["));
         if (cc == '-') {
             SegmentedString::LookAheadResult result = source.lookAhead(dashDashString);
             if (result == SegmentedString::DidMatch) {
@@ -1275,8 +1275,8 @@
             m_token->setForceQuirks();
             return emitAndReconsumeIn(source, HTMLTokenizer::DataState);
         } else {
-            DEFINE_STATIC_LOCAL(String, publicString, (ASCIILiteral("public")));
-            DEFINE_STATIC_LOCAL(String, systemString, (ASCIILiteral("system")));
+            DEFINE_STATIC_LOCAL(String, publicString, ("public"));
+            DEFINE_STATIC_LOCAL(String, systemString, ("system"));
             if (cc == 'P' || cc == 'p') {
                 SegmentedString::LookAheadResult result = source.lookAheadIgnoringCase(publicString);
                 if (result == SegmentedString::DidMatch) {
diff --git a/Source/core/html/parser/XSSAuditor.cpp b/Source/core/html/parser/XSSAuditor.cpp
index 6f50091..47efdac 100644
--- a/Source/core/html/parser/XSSAuditor.cpp
+++ b/Source/core/html/parser/XSSAuditor.cpp
@@ -267,7 +267,7 @@
 
     String httpBodyAsString;
     if (DocumentLoader* documentLoader = document->frame()->loader()->documentLoader()) {
-        DEFINE_STATIC_LOCAL(String, XSSProtectionHeader, (ASCIILiteral("X-XSS-Protection")));
+        DEFINE_STATIC_LOCAL(String, XSSProtectionHeader, ("X-XSS-Protection"));
         String headerValue = documentLoader->response().httpHeaderField(XSSProtectionHeader);
         String errorDetails;
         unsigned errorPosition = 0;
@@ -516,7 +516,7 @@
 
 bool XSSAuditor::eraseDangerousAttributesIfInjected(const FilterTokenRequest& request)
 {
-    DEFINE_STATIC_LOCAL(String, safeJavaScriptURL, (ASCIILiteral("javascript:void(0)")));
+    DEFINE_STATIC_LOCAL(String, safeJavaScriptURL, ("javascript:void(0)"));
 
     bool didBlockScript = false;
     for (size_t i = 0; i < request.token.attributes().size(); ++i) {
diff --git a/Source/core/html/shadow/ClearButtonElement.cpp b/Source/core/html/shadow/ClearButtonElement.cpp
index 3ac4628..c3eb8e9 100644
--- a/Source/core/html/shadow/ClearButtonElement.cpp
+++ b/Source/core/html/shadow/ClearButtonElement.cpp
@@ -46,7 +46,7 @@
 PassRefPtr<ClearButtonElement> ClearButtonElement::create(Document* document, ClearButtonOwner& clearButtonOwner)
 {
     RefPtr<ClearButtonElement> element = adoptRef(new ClearButtonElement(document, clearButtonOwner));
-    element->setPseudo(AtomicString("-webkit-clear-button", AtomicString::ConstructFromLiteral));
+    element->setPart(AtomicString("-webkit-clear-button", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::clearButton());
     return element.release();
 }
diff --git a/Source/core/html/shadow/DateTimeEditElement.cpp b/Source/core/html/shadow/DateTimeEditElement.cpp
index 0bc4369..a8e0222 100644
--- a/Source/core/html/shadow/DateTimeEditElement.cpp
+++ b/Source/core/html/shadow/DateTimeEditElement.cpp
@@ -403,7 +403,7 @@
     DEFINE_STATIC_LOCAL(AtomicString, textPseudoId, ("-webkit-datetime-edit-text", AtomicString::ConstructFromLiteral));
     ASSERT(text.length());
     RefPtr<HTMLDivElement> element = HTMLDivElement::create(m_editElement.document());
-    element->setPseudo(textPseudoId);
+    element->setPart(textPseudoId);
     if (m_parameters.locale.isRTL() && text.length()) {
         Direction dir = direction(text[0]);
         if (dir == SegmentSeparator || dir == WhiteSpaceNeutral || dir == OtherNeutral)
@@ -485,7 +485,7 @@
 PassRefPtr<DateTimeEditElement> DateTimeEditElement::create(Document* document, EditControlOwner& editControlOwner)
 {
     RefPtr<DateTimeEditElement> container = adoptRef(new DateTimeEditElement(document, editControlOwner));
-    container->setPseudo(AtomicString("-webkit-datetime-edit", AtomicString::ConstructFromLiteral));
+    container->setPart(AtomicString("-webkit-datetime-edit", AtomicString::ConstructFromLiteral));
     container->setAttribute(idAttr, ShadowElementNames::dateTimeEdit());
     return container.release();
 }
@@ -652,7 +652,7 @@
     DEFINE_STATIC_LOCAL(AtomicString, fieldsWrapperPseudoId, ("-webkit-datetime-edit-fields-wrapper", AtomicString::ConstructFromLiteral));
     if (!firstChild()) {
         RefPtr<HTMLDivElement> element = HTMLDivElement::create(document());
-        element->setPseudo(fieldsWrapperPseudoId);
+        element->setPart(fieldsWrapperPseudoId);
         appendChild(element.get(), ASSERT_NO_EXCEPTION, AttachLazily);
     }
     Element* fieldsWrapper = fieldsWrapperElement();
diff --git a/Source/core/html/shadow/DateTimeFieldElement.cpp b/Source/core/html/shadow/DateTimeFieldElement.cpp
index 8f266c0..d7ee1e3 100644
--- a/Source/core/html/shadow/DateTimeFieldElement.cpp
+++ b/Source/core/html/shadow/DateTimeFieldElement.cpp
@@ -153,7 +153,7 @@
     setAttribute(aria_valuemaxAttr, String::number(axMaximum));
 
     setAttribute(aria_helpAttr, axHelpText);
-    setPseudo(pseudo);
+    setPart(pseudo);
     appendChild(Text::create(document(), visibleValue()));
 }
 
diff --git a/Source/core/html/shadow/DateTimeFieldElements.cpp b/Source/core/html/shadow/DateTimeFieldElements.cpp
index 8a8a052..fda494d 100644
--- a/Source/core/html/shadow/DateTimeFieldElements.cpp
+++ b/Source/core/html/shadow/DateTimeFieldElements.cpp
@@ -79,7 +79,7 @@
 PassRefPtr<DateTimeDayFieldElement> DateTimeDayFieldElement::create(Document* document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
 {
     DEFINE_STATIC_LOCAL(AtomicString, dayPsuedoId, ("-webkit-datetime-edit-day-field", AtomicString::ConstructFromLiteral));
-    RefPtr<DateTimeDayFieldElement> field = adoptRef(new DateTimeDayFieldElement(document, fieldOwner, placeholder.isEmpty() ? ASCIILiteral("--") : placeholder, range));
+    RefPtr<DateTimeDayFieldElement> field = adoptRef(new DateTimeDayFieldElement(document, fieldOwner, placeholder.isEmpty() ? "--" : placeholder, range));
     field->initialize(dayPsuedoId, AXDayOfMonthFieldText());
     return field.release();
 }
@@ -405,7 +405,7 @@
 PassRefPtr<DateTimeMonthFieldElement> DateTimeMonthFieldElement::create(Document* document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
 {
     DEFINE_STATIC_LOCAL(AtomicString, monthPsuedoId, ("-webkit-datetime-edit-month-field", AtomicString::ConstructFromLiteral));
-    RefPtr<DateTimeMonthFieldElement> field = adoptRef(new DateTimeMonthFieldElement(document, fieldOwner, placeholder.isEmpty() ? ASCIILiteral("--") : placeholder, range));
+    RefPtr<DateTimeMonthFieldElement> field = adoptRef(new DateTimeMonthFieldElement(document, fieldOwner, placeholder.isEmpty() ? "--" : placeholder, range));
     field->initialize(monthPsuedoId, AXMonthFieldText());
     return field.release();
 }
@@ -565,7 +565,7 @@
 // ----------------------------
 
 DateTimeYearFieldElement::DateTimeYearFieldElement(Document* document, FieldOwner& fieldOwner, const DateTimeYearFieldElement::Parameters& parameters)
-    : DateTimeNumericFieldElement(document, fieldOwner, Range(parameters.minimumYear, parameters.maximumYear), Range(DateComponents::minimumYear(), DateComponents::maximumYear()), parameters.placeholder.isEmpty() ? ASCIILiteral("----") : parameters.placeholder)
+    : DateTimeNumericFieldElement(document, fieldOwner, Range(parameters.minimumYear, parameters.maximumYear), Range(DateComponents::minimumYear(), DateComponents::maximumYear()), parameters.placeholder.isEmpty() ? "----" : parameters.placeholder)
     , m_minIsSpecified(parameters.minIsSpecified)
     , m_maxIsSpecified(parameters.maxIsSpecified)
 {
diff --git a/Source/core/html/shadow/DetailsMarkerControl.h b/Source/core/html/shadow/DetailsMarkerControl.h
index 0971195..1b1bf04 100644
--- a/Source/core/html/shadow/DetailsMarkerControl.h
+++ b/Source/core/html/shadow/DetailsMarkerControl.h
@@ -53,7 +53,7 @@
 inline PassRefPtr<DetailsMarkerControl> DetailsMarkerControl::create(Document* document)
 {
     RefPtr<DetailsMarkerControl> element = adoptRef(new DetailsMarkerControl(document));
-    element->setPseudo(AtomicString("-webkit-details-marker", AtomicString::ConstructFromLiteral));
+    element->setPart(AtomicString("-webkit-details-marker", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
diff --git a/Source/core/html/shadow/HTMLContentElement.cpp b/Source/core/html/shadow/HTMLContentElement.cpp
index 385b090..b2e81f6 100644
--- a/Source/core/html/shadow/HTMLContentElement.cpp
+++ b/Source/core/html/shadow/HTMLContentElement.cpp
@@ -87,74 +87,6 @@
         InsertionPoint::parseAttribute(name, value);
 }
 
-static bool validateSubSelector(const CSSSelector* selector)
-{
-    switch (selector->m_match) {
-    case CSSSelector::Tag:
-    case CSSSelector::Id:
-    case CSSSelector::Class:
-    case CSSSelector::Exact:
-    case CSSSelector::Set:
-    case CSSSelector::List:
-    case CSSSelector::Hyphen:
-    case CSSSelector::Contain:
-    case CSSSelector::Begin:
-    case CSSSelector::End:
-        return true;
-    case CSSSelector::PseudoElement:
-        return false;
-    case CSSSelector::PagePseudoClass:
-    case CSSSelector::PseudoClass:
-        break;
-    }
-
-    switch (selector->pseudoType()) {
-    case CSSSelector::PseudoEmpty:
-    case CSSSelector::PseudoLink:
-    case CSSSelector::PseudoVisited:
-    case CSSSelector::PseudoTarget:
-    case CSSSelector::PseudoEnabled:
-    case CSSSelector::PseudoDisabled:
-    case CSSSelector::PseudoChecked:
-    case CSSSelector::PseudoIndeterminate:
-    case CSSSelector::PseudoNthChild:
-    case CSSSelector::PseudoNthLastChild:
-    case CSSSelector::PseudoNthOfType:
-    case CSSSelector::PseudoNthLastOfType:
-    case CSSSelector::PseudoFirstChild:
-    case CSSSelector::PseudoLastChild:
-    case CSSSelector::PseudoFirstOfType:
-    case CSSSelector::PseudoLastOfType:
-    case CSSSelector::PseudoOnlyOfType:
-        return true;
-    default:
-        return false;
-    }
-}
-
-static bool validateSelector(const CSSSelector* selector)
-{
-    ASSERT(selector);
-
-    if (!validateSubSelector(selector))
-        return false;
-
-    const CSSSelector* prevSubSelector = selector;
-    const CSSSelector* subSelector = selector->tagHistory();
-
-    while (subSelector) {
-        if (prevSubSelector->relation() != CSSSelector::SubSelector)
-            return false;
-        if (!validateSubSelector(subSelector))
-            return false;
-
-        prevSubSelector = subSelector;
-        subSelector = subSelector->tagHistory();
-    }
-
-    return true;
-}
-
 bool HTMLContentElement::validateSelect() const
 {
     ASSERT(!m_shouldParseSelect);
@@ -166,7 +98,7 @@
         return false;
 
     for (const CSSSelector* selector = m_selectorList.first(); selector; selector = m_selectorList.next(selector)) {
-        if (!validateSelector(selector))
+        if (!selector->isCompound())
             return false;
     }
 
@@ -193,4 +125,3 @@
 }
 
 }
-
diff --git a/Source/core/html/shadow/MediaControlElementTypes.h b/Source/core/html/shadow/MediaControlElementTypes.h
index 5a3fde8..fb53447 100644
--- a/Source/core/html/shadow/MediaControlElementTypes.h
+++ b/Source/core/html/shadow/MediaControlElementTypes.h
@@ -84,7 +84,7 @@
     virtual bool isShowing() const;
 
     virtual MediaControlElementType displayType() { return m_displayType; }
-    virtual const AtomicString& shadowPseudoId() const = 0;
+    virtual const AtomicString& part() const = 0;
 
     virtual void setMediaController(MediaControllerInterface* controller) { m_mediaController = controller; }
     virtual MediaControllerInterface* mediaController() const { return m_mediaController; }
diff --git a/Source/core/html/shadow/MediaControlElements.cpp b/Source/core/html/shadow/MediaControlElements.cpp
index 3a936fc..9167b9c 100644
--- a/Source/core/html/shadow/MediaControlElements.cpp
+++ b/Source/core/html/shadow/MediaControlElements.cpp
@@ -38,6 +38,7 @@
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/shadow/MediaControls.h"
 #include "core/html/track/TextTrack.h"
+#include "core/html/track/TextTrackRegionList.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
@@ -71,7 +72,7 @@
     return adoptRef(new MediaControlPanelElement(document));
 }
 
-const AtomicString& MediaControlPanelElement::shadowPseudoId() const
+const AtomicString& MediaControlPanelElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-panel", AtomicString::ConstructFromLiteral));
     return id;
@@ -258,7 +259,7 @@
     return adoptRef(new MediaControlPanelEnclosureElement(document));
 }
 
-const AtomicString& MediaControlPanelEnclosureElement::shadowPseudoId() const
+const AtomicString& MediaControlPanelEnclosureElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-enclosure", AtomicString::ConstructFromLiteral));
     return id;
@@ -277,7 +278,7 @@
     return adoptRef(new MediaControlOverlayEnclosureElement(document));
 }
 
-const AtomicString& MediaControlOverlayEnclosureElement::shadowPseudoId() const
+const AtomicString& MediaControlOverlayEnclosureElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-overlay-enclosure", AtomicString::ConstructFromLiteral));
     return id;
@@ -309,7 +310,7 @@
     MediaControlMuteButtonElement::defaultEventHandler(event);
 }
 
-const AtomicString& MediaControlPanelMuteButtonElement::shadowPseudoId() const
+const AtomicString& MediaControlPanelMuteButtonElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-mute-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -330,7 +331,7 @@
     return button.release();
 }
 
-const AtomicString& MediaControlVolumeSliderMuteButtonElement::shadowPseudoId() const
+const AtomicString& MediaControlVolumeSliderMuteButtonElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-volume-slider-mute-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -369,7 +370,7 @@
     setDisplayType(mediaController()->canPlay() ? MediaPlayButton : MediaPauseButton);
 }
 
-const AtomicString& MediaControlPlayButtonElement::shadowPseudoId() const
+const AtomicString& MediaControlPlayButtonElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-play-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -408,7 +409,7 @@
         hide();
 }
 
-const AtomicString& MediaControlOverlayPlayButtonElement::shadowPseudoId() const
+const AtomicString& MediaControlOverlayPlayButtonElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-overlay-play-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -453,7 +454,7 @@
     HTMLInputElement::defaultEventHandler(event);
 }
 
-const AtomicString& MediaControlToggleClosedCaptionsButtonElement::shadowPseudoId() const
+const AtomicString& MediaControlToggleClosedCaptionsButtonElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-toggle-closed-captions-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -526,7 +527,7 @@
 }
 
 
-const AtomicString& MediaControlTimelineElement::shadowPseudoId() const
+const AtomicString& MediaControlTimelineElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-timeline", AtomicString::ConstructFromLiteral));
     return id;
@@ -549,7 +550,7 @@
     return slider.release();
 }
 
-const AtomicString& MediaControlPanelVolumeSliderElement::shadowPseudoId() const
+const AtomicString& MediaControlPanelVolumeSliderElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-volume-slider", AtomicString::ConstructFromLiteral));
     return id;
@@ -591,7 +592,7 @@
     HTMLInputElement::defaultEventHandler(event);
 }
 
-const AtomicString& MediaControlFullscreenButtonElement::shadowPseudoId() const
+const AtomicString& MediaControlFullscreenButtonElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-fullscreen-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -620,7 +621,7 @@
     return id;
 }
 
-const AtomicString& MediaControlTimeRemainingDisplayElement::shadowPseudoId() const
+const AtomicString& MediaControlTimeRemainingDisplayElement::part() const
 {
     return getMediaControlTimeRemainingDisplayElementShadowPseudoId();
 }
@@ -643,7 +644,7 @@
     return id;
 }
 
-const AtomicString& MediaControlCurrentTimeDisplayElement::shadowPseudoId() const
+const AtomicString& MediaControlCurrentTimeDisplayElement::part() const
 {
     return getMediaControlCurrentTimeDisplayElementShadowPseudoId();
 }
@@ -674,7 +675,7 @@
     return id;
 }
 
-const AtomicString& MediaControlTextTrackContainerElement::shadowPseudoId() const
+const AtomicString& MediaControlTextTrackContainerElement::part() const
 {
     return textTrackContainerElementShadowPseudoId();
 }
diff --git a/Source/core/html/shadow/MediaControlElements.h b/Source/core/html/shadow/MediaControlElements.h
index 712ccbb..168ab29 100644
--- a/Source/core/html/shadow/MediaControlElements.h
+++ b/Source/core/html/shadow/MediaControlElements.h
@@ -53,7 +53,7 @@
 private:
     explicit MediaControlPanelElement(Document*);
 
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
     void startDrag(const LayoutPoint& eventLocation);
@@ -84,7 +84,7 @@
 
 private:
     explicit MediaControlPanelEnclosureElement(Document*);
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
 };
 
 // ----------------------------
@@ -95,7 +95,7 @@
 
 private:
     explicit MediaControlOverlayEnclosureElement(Document*);
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
 };
 
 // ----------------------------
@@ -109,7 +109,7 @@
 private:
     explicit MediaControlPanelMuteButtonElement(Document*, MediaControls*);
 
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
     MediaControls* m_controls;
@@ -123,7 +123,7 @@
 
 private:
     explicit MediaControlVolumeSliderMuteButtonElement(Document*);
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
 };
 
 
@@ -139,7 +139,7 @@
 private:
     explicit MediaControlPlayButtonElement(Document*);
 
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -154,7 +154,7 @@
 private:
     explicit MediaControlOverlayPlayButtonElement(Document*);
 
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -171,7 +171,7 @@
 private:
     explicit MediaControlToggleClosedCaptionsButtonElement(Document*, MediaControls*);
 
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -189,7 +189,7 @@
 private:
     explicit MediaControlTimelineElement(Document*, MediaControls*);
 
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
     MediaControls* m_controls;
@@ -208,7 +208,7 @@
 private:
     explicit MediaControlFullscreenButtonElement(Document*);
 
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -220,7 +220,7 @@
 
 private:
     explicit MediaControlPanelVolumeSliderElement(Document*);
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
 };
 
 // ----------------------------
@@ -231,7 +231,7 @@
 
 private:
     explicit MediaControlTimeRemainingDisplayElement(Document*);
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
 };
 
 // ----------------------------
@@ -242,7 +242,7 @@
 
 private:
     explicit MediaControlCurrentTimeDisplayElement(Document*);
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
 };
 
 // ----------------------------
@@ -257,7 +257,7 @@
 
 private:
     explicit MediaControlTextTrackContainerElement(Document*);
-    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
+    virtual const AtomicString& part() const OVERRIDE;
 
     virtual RenderObject* createRenderer(RenderStyle*);
 
diff --git a/Source/core/html/shadow/MediaControls.cpp b/Source/core/html/shadow/MediaControls.cpp
index e562a0e..d14e0c5 100644
--- a/Source/core/html/shadow/MediaControls.cpp
+++ b/Source/core/html/shadow/MediaControls.cpp
@@ -331,7 +331,7 @@
     m_hideFullscreenControlsTimer.stop();
 }
 
-const AtomicString& MediaControls::shadowPseudoId() const
+const AtomicString& MediaControls::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls"));
     return id;
diff --git a/Source/core/html/shadow/MediaControls.h b/Source/core/html/shadow/MediaControls.h
index cb65516..130d03c 100644
--- a/Source/core/html/shadow/MediaControls.h
+++ b/Source/core/html/shadow/MediaControls.h
@@ -125,7 +125,7 @@
 private:
     virtual bool isMediaControls() const { return true; }
 
-    virtual const AtomicString& shadowPseudoId() const;
+    virtual const AtomicString& part() const;
 };
 
 inline MediaControls* toMediaControls(Node* node)
diff --git a/Source/core/html/shadow/MeterShadowElement.cpp b/Source/core/html/shadow/MeterShadowElement.cpp
index 5c9fca5..f92d449 100644
--- a/Source/core/html/shadow/MeterShadowElement.cpp
+++ b/Source/core/html/shadow/MeterShadowElement.cpp
@@ -66,7 +66,7 @@
 PassRefPtr<MeterInnerElement> MeterInnerElement::create(Document* document)
 {
     RefPtr<MeterInnerElement> element = adoptRef(new MeterInnerElement(document));
-    element->setPseudo(AtomicString("-webkit-meter-inner-element", AtomicString::ConstructFromLiteral));
+    element->setPart(AtomicString("-webkit-meter-inner-element", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
@@ -92,7 +92,7 @@
 PassRefPtr<MeterBarElement> MeterBarElement::create(Document* document)
 {
     RefPtr<MeterBarElement> element = adoptRef(new MeterBarElement(document));
-    element->setPseudo(AtomicString("-webkit-meter-bar", AtomicString::ConstructFromLiteral));
+    element->setPart(AtomicString("-webkit-meter-bar", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
diff --git a/Source/core/html/shadow/MeterShadowElement.h b/Source/core/html/shadow/MeterShadowElement.h
index 381c74e..a314267 100644
--- a/Source/core/html/shadow/MeterShadowElement.h
+++ b/Source/core/html/shadow/MeterShadowElement.h
@@ -70,7 +70,7 @@
 public:
     static PassRefPtr<MeterValueElement> create(Document*);
     void setWidthPercentage(double);
-    void updatePseudo() { setPseudo(valuePseudoId()); }
+    void updatePseudo() { setPart(valuePseudoId()); }
 
 private:
     MeterValueElement(Document*);
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
index 821c4d3..81b52fb 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
@@ -39,7 +39,7 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/Page.h"
@@ -112,9 +112,9 @@
     if (!renderer() || !renderer()->isImage())
         return;
     RenderImageResource* resource = toRenderImage(renderer())->imageResource();
-    CachedImage* image = m_isInHoverState ? imageForHoverState() : imageForNormalState();
+    ImageResource* image = m_isInHoverState ? imageForHoverState() : imageForNormalState();
     ASSERT(image);
-    resource->setCachedImage(image);
+    resource->setImageResource(image);
 }
 
 PassRefPtr<RenderStyle> PasswordGeneratorButtonElement::customStyleForRenderer()
@@ -142,20 +142,20 @@
     updateImage();
 }
 
-CachedImage* PasswordGeneratorButtonElement::imageForNormalState()
+ImageResource* PasswordGeneratorButtonElement::imageForNormalState()
 {
     if (!m_cachedImageForNormalState) {
         RefPtr<Image> image = Image::loadPlatformResource("generatePassword");
-        m_cachedImageForNormalState = new CachedImage(image.get());
+        m_cachedImageForNormalState = new ImageResource(image.get());
     }
     return m_cachedImageForNormalState.get();
 }
 
-CachedImage* PasswordGeneratorButtonElement::imageForHoverState()
+ImageResource* PasswordGeneratorButtonElement::imageForHoverState()
 {
     if (!m_cachedImageForHoverState) {
         RefPtr<Image> image = Image::loadPlatformResource("generatePasswordHover");
-        m_cachedImageForHoverState = new CachedImage(image.get());
+        m_cachedImageForHoverState = new ImageResource(image.get());
     }
     return m_cachedImageForHoverState.get();
 }
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.h b/Source/core/html/shadow/PasswordGeneratorButtonElement.h
index b9f654f..2032034 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.h
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class CachedImage;
+class ImageResource;
 class HTMLInputElement;
 class ShadowRoot;
 
@@ -61,14 +61,14 @@
     virtual bool isMouseFocusable() const OVERRIDE { return false; }
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
-    CachedImage* imageForNormalState();
-    CachedImage* imageForHoverState();
+    ImageResource* imageForNormalState();
+    ImageResource* imageForHoverState();
 
     HTMLInputElement* hostInput();
     void updateImage();
 
-    ResourcePtr<CachedImage> m_cachedImageForNormalState;
-    ResourcePtr<CachedImage> m_cachedImageForHoverState;
+    ResourcePtr<ImageResource> m_cachedImageForNormalState;
+    ResourcePtr<ImageResource> m_cachedImageForHoverState;
     bool m_isInHoverState;
 };
 
diff --git a/Source/core/html/shadow/PickerIndicatorElement.cpp b/Source/core/html/shadow/PickerIndicatorElement.cpp
index 96b4b5e..6fbb1cf 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.cpp
+++ b/Source/core/html/shadow/PickerIndicatorElement.cpp
@@ -53,7 +53,7 @@
 PassRefPtr<PickerIndicatorElement> PickerIndicatorElement::create(Document* document, PickerIndicatorOwner& pickerIndicatorOwner)
 {
     RefPtr<PickerIndicatorElement> element = adoptRef(new PickerIndicatorElement(document, pickerIndicatorOwner));
-    element->setPseudo(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
+    element->setPart(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::pickerIndicator());
     return element.release();
 }
diff --git a/Source/core/html/shadow/ProgressShadowElement.cpp b/Source/core/html/shadow/ProgressShadowElement.cpp
index 7720f2f..c1bc2b7 100644
--- a/Source/core/html/shadow/ProgressShadowElement.cpp
+++ b/Source/core/html/shadow/ProgressShadowElement.cpp
@@ -60,13 +60,13 @@
     : ProgressShadowElement(document)
 {
     DEFINE_STATIC_LOCAL(AtomicString, pseudoId, ("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
-    setPseudo(pseudoId);
+    setPart(pseudoId);
 }
 
 PassRefPtr<ProgressInnerElement> ProgressInnerElement::create(Document* document)
 {
     RefPtr<ProgressInnerElement> element = adoptRef(new ProgressInnerElement(document));
-    element->setPseudo(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
+    element->setPart(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
diff --git a/Source/core/html/shadow/ProgressShadowElement.h b/Source/core/html/shadow/ProgressShadowElement.h
index b46a55a..8e02bdc 100644
--- a/Source/core/html/shadow/ProgressShadowElement.h
+++ b/Source/core/html/shadow/ProgressShadowElement.h
@@ -64,7 +64,7 @@
         : ProgressShadowElement(document)
     {
         DEFINE_STATIC_LOCAL(AtomicString, pseudoId, ("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
-        setPseudo(pseudoId);
+        setPart(pseudoId);
     }
 
     static PassRefPtr<ProgressBarElement> create(Document*);
@@ -81,7 +81,7 @@
         : ProgressShadowElement(document)
     {
         DEFINE_STATIC_LOCAL(AtomicString, pseudoId, ("-webkit-progress-value", AtomicString::ConstructFromLiteral));
-        setPseudo(pseudoId);
+        setPart(pseudoId);
     }
 
     static PassRefPtr<ProgressValueElement> create(Document*);
diff --git a/Source/core/html/shadow/ShadowElementNames.cpp b/Source/core/html/shadow/ShadowElementNames.cpp
index 010474a..238be25 100644
--- a/Source/core/html/shadow/ShadowElementNames.cpp
+++ b/Source/core/html/shadow/ShadowElementNames.cpp
@@ -59,6 +59,12 @@
     return name;
 }
 
+const AtomicString& searchDecoration()
+{
+    DEFINE_STATIC_LOCAL(AtomicString, name, ("decoration", AtomicString::ConstructFromLiteral));
+    return name;
+}
+
 }
 
 }
diff --git a/Source/core/html/shadow/ShadowElementNames.h b/Source/core/html/shadow/ShadowElementNames.h
index 8198ec0..ed2f49c 100644
--- a/Source/core/html/shadow/ShadowElementNames.h
+++ b/Source/core/html/shadow/ShadowElementNames.h
@@ -41,6 +41,7 @@
 const AtomicString& spinButton();
 const AtomicString& clearButton();
 const AtomicString& pickerIndicator();
+const AtomicString& searchDecoration();
 
 }
 
diff --git a/Source/core/html/shadow/SliderThumbElement.cpp b/Source/core/html/shadow/SliderThumbElement.cpp
index e444df4..178307d 100644
--- a/Source/core/html/shadow/SliderThumbElement.cpp
+++ b/Source/core/html/shadow/SliderThumbElement.cpp
@@ -176,7 +176,7 @@
     // Force a layout to reset the position of the thumb so the code below doesn't move the thumb to the wrong place.
     // FIXME: Make a custom Render class for the track and move the thumb positioning code there.
     if (track)
-        track->setChildNeedsLayout(true, MarkOnlyThis);
+        track->setChildNeedsLayout(MarkOnlyThis);
 
     RenderFlexibleBox::layout();
 
@@ -216,7 +216,7 @@
     // path, we don't actually update the value here. Instead, we poke at the
     // renderer directly to trigger layout.
     if (renderer())
-        renderer()->setNeedsLayout(true);
+        renderer()->setNeedsLayout();
 }
 
 RenderObject* SliderThumbElement::createRenderer(RenderStyle*)
@@ -252,15 +252,15 @@
 
 void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point)
 {
-    HTMLInputElement* input = hostInput();
-    HTMLElement* trackElement = sliderTrackElementOf(input);
+    RefPtr<HTMLInputElement> input(hostInput());
+    HTMLElement* trackElement = sliderTrackElementOf(input.get());
 
     if (!input->renderer() || !renderBox() || !trackElement->renderBox())
         return;
 
     input->setTextAsOfLastFormControlChangeEvent(input->value());
     LayoutPoint offset = roundedLayoutPoint(input->renderer()->absoluteToLocal(point, UseTransforms));
-    bool isVertical = hasVerticalAppearance(input);
+    bool isVertical = hasVerticalAppearance(input.get());
     bool isLeftToRightDirection = renderBox()->style()->isLeftToRightDirection();
     LayoutUnit trackSize;
     LayoutUnit position;
@@ -307,7 +307,8 @@
 
     // FIXME: This is no longer being set from renderer. Consider updating the method name.
     input->setValueFromRenderer(valueString);
-    renderer()->setNeedsLayout(true);
+    if (renderer())
+        renderer()->setNeedsLayout();
     input->dispatchFormControlChangeEvent();
 }
 
@@ -328,7 +329,7 @@
         frame->eventHandler()->setCapturingMouseEventsNode(0);
     m_inDragMode = false;
     if (renderer())
-        renderer()->setNeedsLayout(true);
+        renderer()->setNeedsLayout();
 }
 
 void SliderThumbElement::defaultEventHandler(Event* event)
@@ -403,23 +404,23 @@
     return toHTMLInputElement(shadowHost());
 }
 
-static const AtomicString& sliderThumbShadowPseudoId()
+static const AtomicString& sliderThumbShadowPartId()
 {
     DEFINE_STATIC_LOCAL(const AtomicString, sliderThumb, ("-webkit-slider-thumb", AtomicString::ConstructFromLiteral));
     return sliderThumb;
 }
 
-static const AtomicString& mediaSliderThumbShadowPseudoId()
+static const AtomicString& mediaSliderThumbShadowPartId()
 {
     DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderThumb, ("-webkit-media-slider-thumb", AtomicString::ConstructFromLiteral));
     return mediaSliderThumb;
 }
 
-const AtomicString& SliderThumbElement::shadowPseudoId() const
+const AtomicString& SliderThumbElement::part() const
 {
     HTMLInputElement* input = hostInput();
     if (!input)
-        return sliderThumbShadowPseudoId();
+        return sliderThumbShadowPartId();
 
     RenderStyle* sliderStyle = input->renderer()->style();
     switch (sliderStyle->appearance()) {
@@ -429,9 +430,9 @@
     case MediaVolumeSliderThumbPart:
     case MediaFullScreenVolumeSliderPart:
     case MediaFullScreenVolumeSliderThumbPart:
-        return mediaSliderThumbShadowPseudoId();
+        return mediaSliderThumbShadowPartId();
     default:
-        return sliderThumbShadowPseudoId();
+        return sliderThumbShadowPartId();
     }
 }
 
@@ -452,7 +453,7 @@
     return new RenderSliderContainer(this);
 }
 
-const AtomicString& SliderContainerElement::shadowPseudoId() const
+const AtomicString& SliderContainerElement::part() const
 {
     DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderContainer, ("-webkit-media-slider-container", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(const AtomicString, sliderContainer, ("-webkit-slider-container", AtomicString::ConstructFromLiteral));
diff --git a/Source/core/html/shadow/SliderThumbElement.h b/Source/core/html/shadow/SliderThumbElement.h
index e6ddcf7..585c1d6 100644
--- a/Source/core/html/shadow/SliderThumbElement.h
+++ b/Source/core/html/shadow/SliderThumbElement.h
@@ -55,7 +55,7 @@
     virtual bool willRespondToMouseMoveEvents() OVERRIDE;
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual const AtomicString& shadowPseudoId() const;
+    virtual const AtomicString& part() const OVERRIDE;
     HTMLInputElement* hostInput() const;
     void setPositionFromPoint(const LayoutPoint&);
 
@@ -120,7 +120,7 @@
 private:
     SliderContainerElement(Document*);
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual const AtomicString& shadowPseudoId() const;
+    virtual const AtomicString& part() const;
 };
 
 }
diff --git a/Source/core/html/shadow/SpinButtonElement.cpp b/Source/core/html/shadow/SpinButtonElement.cpp
index 77a7c75..998f1d4 100644
--- a/Source/core/html/shadow/SpinButtonElement.cpp
+++ b/Source/core/html/shadow/SpinButtonElement.cpp
@@ -56,7 +56,7 @@
 PassRefPtr<SpinButtonElement> SpinButtonElement::create(Document* document, SpinButtonOwner& spinButtonOwner)
 {
     RefPtr<SpinButtonElement> element = adoptRef(new SpinButtonElement(document, spinButtonOwner));
-    element->setPseudo(AtomicString("-webkit-inner-spin-button", AtomicString::ConstructFromLiteral));
+    element->setPart(AtomicString("-webkit-inner-spin-button", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::spinButton());
     return element.release();
 }
diff --git a/Source/core/html/shadow/TextControlInnerElements.cpp b/Source/core/html/shadow/TextControlInnerElements.cpp
index 367c9bd..b1ff5c1 100644
--- a/Source/core/html/shadow/TextControlInnerElements.cpp
+++ b/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -35,6 +35,7 @@
 #include "core/dom/TextEvent.h"
 #include "core/dom/TextEventInputType.h"
 #include "core/html/HTMLInputElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
 #include "core/page/SpeechInput.h"
@@ -131,10 +132,12 @@
 
 PassRefPtr<SearchFieldDecorationElement> SearchFieldDecorationElement::create(Document* document)
 {
-    return adoptRef(new SearchFieldDecorationElement(document));
+    RefPtr<SearchFieldDecorationElement> element = adoptRef(new SearchFieldDecorationElement(document));
+    element->setAttribute(idAttr, ShadowElementNames::searchDecoration());
+    return element.release();
 }
 
-const AtomicString& SearchFieldDecorationElement::shadowPseudoId() const
+const AtomicString& SearchFieldDecorationElement::part() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, resultsDecorationId, ("-webkit-search-results-decoration", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, decorationId, ("-webkit-search-decoration", AtomicString::ConstructFromLiteral));
@@ -180,7 +183,8 @@
 PassRefPtr<SearchFieldCancelButtonElement> SearchFieldCancelButtonElement::create(Document* document)
 {
     RefPtr<SearchFieldCancelButtonElement> element = adoptRef(new SearchFieldCancelButtonElement(document));
-    element->setPseudo(AtomicString("-webkit-search-cancel-button", AtomicString::ConstructFromLiteral));
+    element->setPart(AtomicString("-webkit-search-cancel-button", AtomicString::ConstructFromLiteral));
+    element->setAttribute(idAttr, ShadowElementNames::clearButton());
     return element.release();
 }
 
@@ -268,7 +272,7 @@
 PassRefPtr<InputFieldSpeechButtonElement> InputFieldSpeechButtonElement::create(Document* document)
 {
     RefPtr<InputFieldSpeechButtonElement> element = adoptRef(new InputFieldSpeechButtonElement(document));
-    element->setPseudo(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
+    element->setPart(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
diff --git a/Source/core/html/shadow/TextControlInnerElements.h b/Source/core/html/shadow/TextControlInnerElements.h
index f3f6a8c..955b8f2 100644
--- a/Source/core/html/shadow/TextControlInnerElements.h
+++ b/Source/core/html/shadow/TextControlInnerElements.h
@@ -77,7 +77,7 @@
 
 private:
     SearchFieldDecorationElement(Document*);
-    virtual const AtomicString& shadowPseudoId() const;
+    virtual const AtomicString& part() const OVERRIDE;
     virtual bool supportsFocus() const OVERRIDE { return false; }
 };
 
diff --git a/Source/core/html/track/InbandTextTrack.cpp b/Source/core/html/track/InbandTextTrack.cpp
index b33f087..b1076d4 100644
--- a/Source/core/html/track/InbandTextTrack.cpp
+++ b/Source/core/html/track/InbandTextTrack.cpp
@@ -162,11 +162,11 @@
         cue->setForegroundColor(cueData->foregroundColor().rgb());
 
     if (cueData->align() == GenericCueData::Start)
-        cue->setAlign(ASCIILiteral("start"), IGNORE_EXCEPTION);
+        cue->setAlign("start", IGNORE_EXCEPTION);
     else if (cueData->align() == GenericCueData::Middle)
-        cue->setAlign(ASCIILiteral("middle"), IGNORE_EXCEPTION);
+        cue->setAlign("middle", IGNORE_EXCEPTION);
     else if (cueData->align() == GenericCueData::End)
-        cue->setAlign(ASCIILiteral("end"), IGNORE_EXCEPTION);
+        cue->setAlign("end", IGNORE_EXCEPTION);
     cue->setSnapToLines(false);
 
     if (hasCue(cue.get())) {
diff --git a/Source/core/html/track/LoadableTextTrack.cpp b/Source/core/html/track/LoadableTextTrack.cpp
index 30b0c53..51c9722 100644
--- a/Source/core/html/track/LoadableTextTrack.cpp
+++ b/Source/core/html/track/LoadableTextTrack.cpp
@@ -29,6 +29,7 @@
 
 #include "core/html/HTMLTrackElement.h"
 #include "core/html/track/TextTrackCueList.h"
+#include "core/html/track/TextTrackRegionList.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/track/TextTrack.cpp b/Source/core/html/track/TextTrack.cpp
index 6827910..6a392ef 100644
--- a/Source/core/html/track/TextTrack.cpp
+++ b/Source/core/html/track/TextTrack.cpp
@@ -339,7 +339,7 @@
     regionList->add(region);
 }
 
-void TextTrack::removeRegion(TextTrackRegion* region, ExceptionCode &es)
+void TextTrack::removeRegion(TextTrackRegion* region, ExceptionState &es)
 {
     if (!region)
         return;
diff --git a/Source/core/html/track/TextTrack.idl b/Source/core/html/track/TextTrack.idl
index 8b2e8aa..36e19d9 100644
--- a/Source/core/html/track/TextTrack.idl
+++ b/Source/core/html/track/TextTrack.idl
@@ -34,7 +34,7 @@
 
     readonly attribute TextTrackCueList cues;
     readonly attribute TextTrackCueList activeCues;
-             attribute EventListener oncuechange;
+             attribute EventHandler oncuechange;
 
     void addCue(TextTrackCue cue);
     [RaisesException] void removeCue(TextTrackCue cue);
diff --git a/Source/core/html/track/TextTrackCue.cpp b/Source/core/html/track/TextTrackCue.cpp
index 1e6c5e2..7c42af0 100644
--- a/Source/core/html/track/TextTrackCue.cpp
+++ b/Source/core/html/track/TextTrackCue.cpp
@@ -42,6 +42,7 @@
 #include "core/html/HTMLDivElement.h"
 #include "core/html/track/TextTrack.h"
 #include "core/html/track/TextTrackCueList.h"
+#include "core/html/track/TextTrackRegionList.h"
 #include "core/html/track/WebVTTElement.h"
 #include "core/html/track/WebVTTParser.h"
 #include "core/rendering/RenderTextTrackCue.h"
@@ -56,19 +57,19 @@
 
 static const String& startKeyword()
 {
-    DEFINE_STATIC_LOCAL(const String, start, (ASCIILiteral("start")));
+    DEFINE_STATIC_LOCAL(const String, start, ("start"));
     return start;
 }
 
 static const String& middleKeyword()
 {
-    DEFINE_STATIC_LOCAL(const String, middle, (ASCIILiteral("middle")));
+    DEFINE_STATIC_LOCAL(const String, middle, ("middle"));
     return middle;
 }
 
 static const String& endKeyword()
 {
-    DEFINE_STATIC_LOCAL(const String, end, (ASCIILiteral("end")));
+    DEFINE_STATIC_LOCAL(const String, end, ("end"));
     return end;
 }
 
@@ -79,13 +80,13 @@
 
 static const String& verticalGrowingLeftKeyword()
 {
-    DEFINE_STATIC_LOCAL(const String, verticalrl, (ASCIILiteral("rl")));
+    DEFINE_STATIC_LOCAL(const String, verticalrl, ("rl"));
     return verticalrl;
 }
 
 static const String& verticalGrowingRightKeyword()
 {
-    DEFINE_STATIC_LOCAL(const String, verticallr, (ASCIILiteral("lr")));
+    DEFINE_STATIC_LOCAL(const String, verticallr, ("lr"));
     return verticallr;
 }
 
@@ -95,7 +96,7 @@
     : HTMLDivElement(divTag, document)
     , m_cue(cue)
 {
-    setPseudo(textTrackCueBoxShadowPseudoId());
+    setPart(textTrackCueBoxShadowPseudoId());
 }
 
 TextTrackCue* TextTrackCueBox::getCue() const
@@ -607,7 +608,7 @@
 
 void TextTrackCue::determineTextDirection()
 {
-    DEFINE_STATIC_LOCAL(const String, rtTag, (ASCIILiteral("rt")));
+    DEFINE_STATIC_LOCAL(const String, rtTag, ("rt"));
     createWebVTTNodeTree();
 
     // Apply the Unicode Bidirectional Algorithm's Paragraph Level steps to the
@@ -738,7 +739,7 @@
 
 void TextTrackCue::markFutureAndPastNodes(ContainerNode* root, double previousTimestamp, double movieTime)
 {
-    DEFINE_STATIC_LOCAL(const String, timestampTag, (ASCIILiteral("timestamp")));
+    DEFINE_STATIC_LOCAL(const String, timestampTag, ("timestamp"));
 
     bool isPastNode = true;
     double currentTimestamp = previousTimestamp;
@@ -803,7 +804,7 @@
     // background box.
 
     // Note: This is contained by default in m_cueBackgroundBox.
-    m_cueBackgroundBox->setPseudo(cueShadowPseudoId());
+    m_cueBackgroundBox->setPart(cueShadowPseudoId());
     displayTree->appendChild(m_cueBackgroundBox, ASSERT_NO_EXCEPTION, AttachLazily);
 
     // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not
@@ -878,13 +879,13 @@
 
 TextTrackCue::CueSetting TextTrackCue::settingName(const String& name)
 {
-    DEFINE_STATIC_LOCAL(const String, verticalKeyword, (ASCIILiteral("vertical")));
-    DEFINE_STATIC_LOCAL(const String, lineKeyword, (ASCIILiteral("line")));
-    DEFINE_STATIC_LOCAL(const String, positionKeyword, (ASCIILiteral("position")));
-    DEFINE_STATIC_LOCAL(const String, sizeKeyword, (ASCIILiteral("size")));
-    DEFINE_STATIC_LOCAL(const String, alignKeyword, (ASCIILiteral("align")));
+    DEFINE_STATIC_LOCAL(const String, verticalKeyword, ("vertical"));
+    DEFINE_STATIC_LOCAL(const String, lineKeyword, ("line"));
+    DEFINE_STATIC_LOCAL(const String, positionKeyword, ("position"));
+    DEFINE_STATIC_LOCAL(const String, sizeKeyword, ("size"));
+    DEFINE_STATIC_LOCAL(const String, alignKeyword, ("align"));
 #if ENABLE(WEBVTT_REGIONS)
-    DEFINE_STATIC_LOCAL(const String, regionIdKeyword, (ASCIILiteral("region")));
+    DEFINE_STATIC_LOCAL(const String, regionIdKeyword, ("region"));
 #endif
 
     if (name == verticalKeyword)
diff --git a/Source/core/html/track/TextTrackCue.idl b/Source/core/html/track/TextTrackCue.idl
index f398a9a..d379587 100644
--- a/Source/core/html/track/TextTrackCue.idl
+++ b/Source/core/html/track/TextTrackCue.idl
@@ -45,8 +45,8 @@
     attribute DOMString text;
     DocumentFragment getCueAsHTML();
 
-    attribute EventListener onenter;
-    attribute EventListener onexit;
+    attribute EventHandler onenter;
+    attribute EventHandler onexit;
 
     [Conditional=WEBVTT_REGIONS] attribute DOMString regionId;
 };
diff --git a/Source/core/html/track/TextTrackList.idl b/Source/core/html/track/TextTrackList.idl
index a6e51b3..d52c548 100644
--- a/Source/core/html/track/TextTrackList.idl
+++ b/Source/core/html/track/TextTrackList.idl
@@ -30,6 +30,6 @@
     readonly attribute unsigned long length;
     getter TextTrack item(unsigned long index);
 
-    attribute EventListener onaddtrack;
+    attribute EventHandler onaddtrack;
 };
 
diff --git a/Source/core/html/track/TextTrackRegion.cpp b/Source/core/html/track/TextTrackRegion.cpp
index 4a93ac6..51a91b6 100644
--- a/Source/core/html/track/TextTrackRegion.cpp
+++ b/Source/core/html/track/TextTrackRegion.cpp
@@ -468,11 +468,11 @@
         0.0,
         CSSPrimitiveValue::CSS_PX);
 
-    m_cueContainer->setPseudo(textTrackCueContainerShadowPseudoId());
+    m_cueContainer->setPart(textTrackCueContainerShadowPseudoId());
     m_regionDisplayTree->appendChild(m_cueContainer);
 
     // 7.5 Every WebVTT region object is initialised with the following CSS
-    m_regionDisplayTree->setPseudo(textTrackRegionShadowPseudoId());
+    m_regionDisplayTree->setPart(textTrackRegionShadowPseudoId());
 }
 
 void TextTrackRegion::startTimer()
diff --git a/Source/core/html/track/WebVTTParser.cpp b/Source/core/html/track/WebVTTParser.cpp
index 4a7b524..4b2dfc2 100644
--- a/Source/core/html/track/WebVTTParser.cpp
+++ b/Source/core/html/track/WebVTTParser.cpp
@@ -328,13 +328,16 @@
     // 4.8.10.13.4 WebVTT cue text parsing rules and
     // 4.8.10.13.5 WebVTT cue text DOM construction rules.
 
-    if (!text.length())
-        return 0;
-
     ASSERT(m_scriptExecutionContext->isDocument());
     Document* document = toDocument(m_scriptExecutionContext);
 
     RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
+
+    if (!text.length()) {
+        fragment->parserAppendChild(Text::create(document, ""));
+        return fragment;
+    }
+
     m_currentNode = fragment;
     m_tokenizer->reset();
     m_token.clear();
diff --git a/Source/core/inspector/InspectorApplicationCacheAgent.cpp b/Source/core/inspector/InspectorApplicationCacheAgent.cpp
index 7ea825a..608b7bf 100644
--- a/Source/core/inspector/InspectorApplicationCacheAgent.cpp
+++ b/Source/core/inspector/InspectorApplicationCacheAgent.cpp
@@ -43,7 +43,7 @@
 }
 
 InspectorApplicationCacheAgent::InspectorApplicationCacheAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorPageAgent* pageAgent)
-    : InspectorBaseAgent<InspectorApplicationCacheAgent>(ASCIILiteral("ApplicationCache"), instrumentingAgents, state)
+    : InspectorBaseAgent<InspectorApplicationCacheAgent>("ApplicationCache", instrumentingAgents, state)
     , m_pageAgent(pageAgent)
     , m_frontend(0)
 {
diff --git a/Source/core/inspector/InspectorCSSAgent.cpp b/Source/core/inspector/InspectorCSSAgent.cpp
index 99a5fac..45205fe 100644
--- a/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/Source/core/inspector/InspectorCSSAgent.cpp
@@ -111,10 +111,10 @@
 
 static unsigned computePseudoClassMask(JSONArray* pseudoClassArray)
 {
-    DEFINE_STATIC_LOCAL(String, active, (ASCIILiteral("active")));
-    DEFINE_STATIC_LOCAL(String, hover, (ASCIILiteral("hover")));
-    DEFINE_STATIC_LOCAL(String, focus, (ASCIILiteral("focus")));
-    DEFINE_STATIC_LOCAL(String, visited, (ASCIILiteral("visited")));
+    DEFINE_STATIC_LOCAL(String, active, ("active"));
+    DEFINE_STATIC_LOCAL(String, hover, ("hover"));
+    DEFINE_STATIC_LOCAL(String, focus, ("focus"));
+    DEFINE_STATIC_LOCAL(String, visited, ("visited"));
     if (!pseudoClassArray || !pseudoClassArray->length())
         return PseudoNone;
 
diff --git a/Source/core/inspector/InspectorController.cpp b/Source/core/inspector/InspectorController.cpp
index 750904c..a9cb37b 100644
--- a/Source/core/inspector/InspectorController.cpp
+++ b/Source/core/inspector/InspectorController.cpp
@@ -138,7 +138,7 @@
 
     m_agents.append(InspectorInputAgent::create(m_instrumentingAgents.get(), m_state.get(), page, inspectorClient));
 
-    m_agents.append(InspectorLayerTreeAgent::create(m_instrumentingAgents.get(), m_state.get()));
+    m_agents.append(InspectorLayerTreeAgent::create(m_instrumentingAgents.get(), m_state.get(), domAgent, page));
 
     ASSERT_ARG(inspectorClient, inspectorClient);
     m_injectedScriptManager->injectedScriptHost()->init(m_instrumentingAgents.get(), pageScriptDebugServer);
diff --git a/Source/core/inspector/InspectorFileSystemAgent.cpp b/Source/core/inspector/InspectorFileSystemAgent.cpp
index 15add73..6a75eee 100644
--- a/Source/core/inspector/InspectorFileSystemAgent.cpp
+++ b/Source/core/inspector/InspectorFileSystemAgent.cpp
@@ -48,7 +48,7 @@
 #include "modules/filesystem/DirectoryEntry.h"
 #include "modules/filesystem/DirectoryReader.h"
 #include "modules/filesystem/EntriesCallback.h"
-#include "modules/filesystem/EntryArray.h"
+#include "modules/filesystem/Entry.h"
 #include "modules/filesystem/EntryCallback.h"
 #include "modules/filesystem/ErrorCallback.h"
 #include "modules/filesystem/FileCallback.h"
@@ -82,14 +82,14 @@
 template<typename BaseCallback, typename Handler, typename Argument>
 class CallbackDispatcher : public BaseCallback {
 public:
-    typedef bool (Handler::*HandlingMethod)(Argument*);
+    typedef bool (Handler::*HandlingMethod)(Argument);
 
     static PassRefPtr<CallbackDispatcher> create(PassRefPtr<Handler> handler, HandlingMethod handlingMethod)
     {
         return adoptRef(new CallbackDispatcher(handler, handlingMethod));
     }
 
-    virtual bool handleEvent(Argument* argument) OVERRIDE
+    virtual bool handleEvent(Argument argument) OVERRIDE
     {
         return (m_handler.get()->*m_handlingMethod)(argument);
     }
@@ -107,7 +107,7 @@
 class CallbackDispatcherFactory {
 public:
     template<typename Handler, typename Argument>
-    static PassRefPtr<CallbackDispatcher<BaseCallback, Handler, Argument> > create(Handler* handler, bool (Handler::*handlingMethod)(Argument*))
+    static PassRefPtr<CallbackDispatcher<BaseCallback, Handler, Argument> > create(Handler* handler, bool (Handler::*handlingMethod)(Argument))
     {
         return CallbackDispatcher<BaseCallback, Handler, Argument>::create(PassRefPtr<Handler>(handler), handlingMethod);
     }
@@ -199,7 +199,7 @@
     }
 
     bool didGetEntry(Entry*);
-    bool didReadDirectoryEntries(EntryArray*);
+    bool didReadDirectoryEntries(const EntryVector&);
 
     void reportResult(FileError::ErrorCode errorCode, PassRefPtr<Array<TypeBuilder::FileSystem::Entry> > entries = 0)
     {
@@ -261,15 +261,15 @@
     m_directoryReader->readEntries(successCallback, errorCallback);
 }
 
-bool DirectoryContentRequest::didReadDirectoryEntries(EntryArray* entries)
+bool DirectoryContentRequest::didReadDirectoryEntries(const EntryVector& entries)
 {
-    if (!entries->length()) {
+    if (entries.isEmpty()) {
         reportResult(static_cast<FileError::ErrorCode>(0), m_entries);
         return true;
     }
 
-    for (unsigned i = 0; i < entries->length(); ++i) {
-        Entry* entry = entries->item(i);
+    for (size_t i = 0; i < entries.size(); ++i) {
+        RefPtr<Entry> entry = entries[i];
         RefPtr<TypeBuilder::FileSystem::Entry> entryForFrontend = TypeBuilder::FileSystem::Entry::create()
             .setUrl(entry->toURL())
             .setName(entry->name())
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.cpp b/Source/core/inspector/InspectorIndexedDBAgent.cpp
index 59caf6d..017b547 100644
--- a/Source/core/inspector/InspectorIndexedDBAgent.cpp
+++ b/Source/core/inspector/InspectorIndexedDBAgent.cpp
@@ -328,10 +328,10 @@
     if (!key->getString("type", &type))
         return 0;
 
-    DEFINE_STATIC_LOCAL(String, number, (ASCIILiteral("number")));
-    DEFINE_STATIC_LOCAL(String, string, (ASCIILiteral("string")));
-    DEFINE_STATIC_LOCAL(String, date, (ASCIILiteral("date")));
-    DEFINE_STATIC_LOCAL(String, array, (ASCIILiteral("array")));
+    DEFINE_STATIC_LOCAL(String, number, ("number"));
+    DEFINE_STATIC_LOCAL(String, string, ("string"));
+    DEFINE_STATIC_LOCAL(String, date, ("date"));
+    DEFINE_STATIC_LOCAL(String, array, ("array"));
 
     if (type == number) {
         double number;
diff --git a/Source/core/inspector/InspectorInstrumentation.idl b/Source/core/inspector/InspectorInstrumentation.idl
index 7900bd4..a9bd1ae 100644
--- a/Source/core/inspector/InspectorInstrumentation.idl
+++ b/Source/core/inspector/InspectorInstrumentation.idl
@@ -410,12 +410,6 @@
 
     [LayerTree]
     void layerTreeDidChange(Page*);
-
-    [LayerTree]
-    void renderLayerDestroyed(Page*, const RenderLayer*);
-
-    [LayerTree]
-    void pseudoElementDestroyed(Page*, PseudoElement*);
 }
 
 interface InspectorConsoleInstrumentation {
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.cpp b/Source/core/inspector/InspectorLayerTreeAgent.cpp
index 88f729a..3c0fb1f 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.cpp
+++ b/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -33,7 +34,6 @@
 #include "core/inspector/InspectorLayerTreeAgent.h"
 
 #include "InspectorFrontend.h"
-#include "core/dom/PseudoElement.h"
 #include "core/inspector/IdentifiersFactory.h"
 #include "core/inspector/InspectorDOMAgent.h"
 #include "core/inspector/InspectorState.h"
@@ -44,6 +44,8 @@
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerBacking.h"
 #include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderView.h"
+#include "public/platform/WebLayer.h"
 
 namespace WebCore {
 
@@ -51,15 +53,42 @@
 static const char layerTreeAgentEnabled[] = "layerTreeAgentEnabled";
 };
 
-InspectorLayerTreeAgent::InspectorLayerTreeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
+static PassRefPtr<TypeBuilder::LayerTree::Layer> buildObjectForLayer(GraphicsLayer* graphicsLayer, int nodeId, bool forceRoot)
+{
+    RefPtr<TypeBuilder::LayerTree::Layer> layerObject = TypeBuilder::LayerTree::Layer::create()
+        .setLayerId(String::number(graphicsLayer->platformLayer()->id()))
+        .setNodeId(nodeId)
+        .setOffsetX(graphicsLayer->position().x())
+        .setOffsetY(graphicsLayer->position().y())
+        .setWidth(graphicsLayer->size().width())
+        .setHeight(graphicsLayer->size().height())
+        .setPaintCount(graphicsLayer->repaintCount());
+
+    // Artificially clip tree at root renger layer's graphic layer -- it might be not the real
+    // root of graphics layer hierarchy, as platform adds containing layers (e.g. for overflosw scroll).
+    if (graphicsLayer->parent() && !forceRoot)
+        layerObject->setParentLayerId(String::number(graphicsLayer->parent()->platformLayer()->id()));
+
+    return layerObject;
+}
+
+static void maybeAddGraphicsLayer(GraphicsLayer* graphicsLayer, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers, bool forceRoot = false)
+{
+    if (!graphicsLayer)
+        return;
+    layers->addItem(buildObjectForLayer(graphicsLayer, nodeId, forceRoot));
+}
+
+InspectorLayerTreeAgent::InspectorLayerTreeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorDOMAgent* domAgent, Page* page)
     : InspectorBaseAgent<InspectorLayerTreeAgent>("LayerTree", instrumentingAgents, state)
     , m_frontend(0)
+    , m_page(page)
+    , m_domAgent(domAgent)
 {
 }
 
 InspectorLayerTreeAgent::~InspectorLayerTreeAgent()
 {
-    reset();
 }
 
 void InspectorLayerTreeAgent::setFrontend(InspectorFrontend* frontend)
@@ -79,14 +108,6 @@
         enable(0);
 }
 
-void InspectorLayerTreeAgent::reset()
-{
-    m_documentLayerToIdMap.clear();
-    m_idToLayer.clear();
-    m_pseudoElementToIdMap.clear();
-    m_idToPseudoElement.clear();
-}
-
 void InspectorLayerTreeAgent::enable(ErrorString*)
 {
     m_state->setBoolean(LayerTreeAgentState::layerTreeAgentEnabled, true);
@@ -105,8 +126,6 @@
 {
     if (loader->frame() != frame->page()->mainFrame())
         return;
-
-    reset();
 }
 
 void InspectorLayerTreeAgent::layerTreeDidChange()
@@ -114,35 +133,52 @@
     m_frontend->layerTreeDidChange();
 }
 
-void InspectorLayerTreeAgent::renderLayerDestroyed(const RenderLayer* renderLayer)
-{
-    unbind(renderLayer);
-}
-
-void InspectorLayerTreeAgent::pseudoElementDestroyed(PseudoElement* pseudoElement)
-{
-    unbindPseudoElement(pseudoElement);
-}
-
-void InspectorLayerTreeAgent::layersForNode(ErrorString* errorString, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
+void InspectorLayerTreeAgent::getLayers(ErrorString* errorString, const int* nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
 {
     layers = TypeBuilder::Array<TypeBuilder::LayerTree::Layer>::create();
 
-    Node* node = m_instrumentingAgents->inspectorDOMAgent()->nodeForId(nodeId);
+    RenderView* renderView = m_page->mainFrame()->contentRenderer();
+    RenderLayerCompositor* compositor = renderView ? renderView->compositor() : 0;
+    if (!compositor) {
+        *errorString = "Not in compositing mode";
+        return;
+    }
+    if (!nodeId) {
+        gatherLayersUsingRenderLayerHierarchy(errorString, compositor->rootRenderLayer(), layers);
+        return;
+    }
+    Node* node = m_instrumentingAgents->inspectorDOMAgent()->nodeForId(*nodeId);
     if (!node) {
         *errorString = "Provided node id doesn't match any known node";
         return;
     }
-
     RenderObject* renderer = node->renderer();
     if (!renderer) {
         *errorString = "Node for provided node id doesn't have a renderer";
         return;
     }
-
     gatherLayersUsingRenderObjectHierarchy(errorString, renderer, layers);
 }
 
+void InspectorLayerTreeAgent::addRenderLayerBacking(ErrorString* errorString, RenderLayerBacking* layerBacking, Node* node, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
+{
+    int nodeId = idForNode(errorString, node);
+    RenderLayerCompositor* compositor = layerBacking->owningLayer()->compositor();
+    bool forceRoot = layerBacking->owningLayer()->isRootLayer();
+    if (layerBacking->ancestorClippingLayer()) {
+        maybeAddGraphicsLayer(layerBacking->ancestorClippingLayer(), nodeId, layers, forceRoot);
+        forceRoot = false;
+    }
+    maybeAddGraphicsLayer(layerBacking->graphicsLayer(), nodeId, layers, forceRoot);
+    maybeAddGraphicsLayer(layerBacking->clippingLayer(), nodeId, layers);
+    maybeAddGraphicsLayer(layerBacking->foregroundLayer(), nodeId, layers);
+    maybeAddGraphicsLayer(layerBacking->backgroundLayer(), nodeId, layers);
+    maybeAddGraphicsLayer(layerBacking->scrollingLayer(), nodeId, layers);
+    maybeAddGraphicsLayer(layerBacking->scrollingContentsLayer(), nodeId, layers);
+    maybeAddGraphicsLayer(layerBacking->layerForHorizontalScrollbar(), nodeId, layers);
+    maybeAddGraphicsLayer(layerBacking->layerForVerticalScrollbar(), nodeId, layers);
+}
+
 void InspectorLayerTreeAgent::gatherLayersUsingRenderObjectHierarchy(ErrorString* errorString, RenderObject* renderer, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
 {
     if (renderer->hasLayer()) {
@@ -156,58 +192,14 @@
 
 void InspectorLayerTreeAgent::gatherLayersUsingRenderLayerHierarchy(ErrorString* errorString, RenderLayer* renderLayer, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
 {
-    if (renderLayer->isComposited())
-        layers->addItem(buildObjectForLayer(errorString, renderLayer));
-
+    if (renderLayer->isComposited()) {
+        Node* node = (renderLayer->isReflection() ? renderLayer->parent() : renderLayer)->renderer()->generatingNode();
+        addRenderLayerBacking(errorString, renderLayer->backing(), node, layers);
+    }
     for (renderLayer = renderLayer->firstChild(); renderLayer; renderLayer = renderLayer->nextSibling())
         gatherLayersUsingRenderLayerHierarchy(errorString, renderLayer, layers);
 }
 
-PassRefPtr<TypeBuilder::LayerTree::Layer> InspectorLayerTreeAgent::buildObjectForLayer(ErrorString* errorString, RenderLayer* renderLayer)
-{
-    RenderObject* renderer = renderLayer->renderer();
-    RenderLayerBacking* backing = renderLayer->backing();
-    Node* node = renderer->node();
-
-    bool isReflection = renderLayer->isReflection();
-    bool isGenerated = (isReflection ? renderer->parent() : renderer)->isBeforeOrAfterContent();
-
-    if (isReflection && isGenerated)
-        node = renderer->parent()->generatingNode();
-    else if (isGenerated)
-        node = renderer->generatingNode();
-    else if (isReflection)
-        node = renderer->parent()->node();
-
-    // Basic set of properties.
-    RefPtr<TypeBuilder::LayerTree::Layer> layerObject = TypeBuilder::LayerTree::Layer::create()
-        .setLayerId(bind(renderLayer))
-        .setNodeId(idForNode(errorString, node))
-        .setBounds(buildObjectForIntRect(renderer->absoluteBoundingBoxRect()))
-        .setMemory(backing->backingStoreMemoryEstimate())
-        .setCompositedBounds(buildObjectForIntRect(backing->compositedBounds()))
-        .setPaintCount(backing->graphicsLayer()->repaintCount());
-
-    if (node && node->shadowHost())
-        layerObject->setIsInShadowTree(true);
-
-    if (isReflection)
-        layerObject->setIsReflection(true);
-
-    if (isGenerated) {
-        if (isReflection)
-            renderer = renderer->parent();
-        layerObject->setIsGeneratedContent(true);
-        layerObject->setPseudoElementId(bindPseudoElement(static_cast<PseudoElement*>(renderer->node())));
-        if (renderer->isBeforeContent())
-            layerObject->setPseudoClass("before");
-        else if (renderer->isAfterContent())
-            layerObject->setPseudoClass("after");
-    }
-
-    return layerObject;
-}
-
 int InspectorLayerTreeAgent::idForNode(ErrorString* errorString, Node* node)
 {
     InspectorDOMAgent* domAgent = m_instrumentingAgents->inspectorDOMAgent();
@@ -219,139 +211,4 @@
     return nodeId;
 }
 
-PassRefPtr<TypeBuilder::LayerTree::IntRect> InspectorLayerTreeAgent::buildObjectForIntRect(const IntRect& rect)
-{
-    return TypeBuilder::LayerTree::IntRect::create()
-        .setX(rect.x())
-        .setY(rect.y())
-        .setWidth(rect.width())
-        .setHeight(rect.height()).release();
-}
-
-void InspectorLayerTreeAgent::reasonsForCompositingLayer(ErrorString* errorString, const String& layerId, RefPtr<TypeBuilder::LayerTree::CompositingReasons>& compositingReasons)
-{
-    const RenderLayer* renderLayer = m_idToLayer.get(layerId);
-
-    if (!renderLayer) {
-        *errorString = "Could not find a bound layer for the provided id";
-        return;
-    }
-
-    CompositingReasons reasonsBitmask = renderLayer->compositor()->reasonsForCompositing(renderLayer);
-    compositingReasons = TypeBuilder::LayerTree::CompositingReasons::create();
-
-    if (reasonsBitmask & CompositingReason3DTransform)
-        compositingReasons->setTransform3D(true);
-
-    if (reasonsBitmask & CompositingReasonVideo)
-        compositingReasons->setVideo(true);
-    else if (reasonsBitmask & CompositingReasonCanvas)
-        compositingReasons->setCanvas(true);
-    else if (reasonsBitmask & CompositingReasonPlugin)
-        compositingReasons->setPlugin(true);
-    else if (reasonsBitmask & CompositingReasonIFrame)
-        compositingReasons->setIFrame(true);
-
-    if (reasonsBitmask & CompositingReasonBackfaceVisibilityHidden)
-        compositingReasons->setBackfaceVisibilityHidden(true);
-
-    if (reasonsBitmask & CompositingReasonClipsCompositingDescendants)
-        compositingReasons->setClipsCompositingDescendants(true);
-
-    if (reasonsBitmask & CompositingReasonAnimation)
-        compositingReasons->setAnimation(true);
-
-    if (reasonsBitmask & CompositingReasonFilters)
-        compositingReasons->setFilters(true);
-
-    if (reasonsBitmask & CompositingReasonPositionFixed)
-        compositingReasons->setPositionFixed(true);
-
-    if (reasonsBitmask & CompositingReasonPositionSticky)
-        compositingReasons->setPositionSticky(true);
-
-    if (reasonsBitmask & CompositingReasonOverflowScrollingTouch)
-        compositingReasons->setOverflowScrollingTouch(true);
-
-    if (reasonsBitmask & CompositingReasonAssumedOverlap)
-        compositingReasons->setStacking(true);
-
-    if (reasonsBitmask & CompositingReasonOverlap)
-        compositingReasons->setOverlap(true);
-
-    if (reasonsBitmask & CompositingReasonNegativeZIndexChildren)
-        compositingReasons->setNegativeZIndexChildren(true);
-
-    if (reasonsBitmask & CompositingReasonTransformWithCompositedDescendants)
-        compositingReasons->setTransformWithCompositedDescendants(true);
-
-    if (reasonsBitmask & CompositingReasonOpacityWithCompositedDescendants)
-        compositingReasons->setOpacityWithCompositedDescendants(true);
-
-    if (reasonsBitmask & CompositingReasonMaskWithCompositedDescendants)
-        compositingReasons->setMaskWithCompositedDescendants(true);
-
-    if (reasonsBitmask & CompositingReasonReflectionWithCompositedDescendants)
-        compositingReasons->setReflectionWithCompositedDescendants(true);
-
-    if (reasonsBitmask & CompositingReasonFilterWithCompositedDescendants)
-        compositingReasons->setFilterWithCompositedDescendants(true);
-
-    if (reasonsBitmask & CompositingReasonBlendingWithCompositedDescendants)
-        compositingReasons->setBlendingWithCompositedDescendants(true);
-
-    if (reasonsBitmask & CompositingReasonPerspective)
-        compositingReasons->setPerspective(true);
-
-    if (reasonsBitmask & CompositingReasonPreserve3D)
-        compositingReasons->setPreserve3D(true);
-
-    if (reasonsBitmask & CompositingReasonRoot)
-        compositingReasons->setRoot(true);
-}
-
-String InspectorLayerTreeAgent::bind(const RenderLayer* layer)
-{
-    if (!layer)
-        return emptyString();
-    String identifier = m_documentLayerToIdMap.get(layer);
-    if (identifier.isNull()) {
-        identifier = IdentifiersFactory::createIdentifier();
-        m_documentLayerToIdMap.set(layer, identifier);
-        m_idToLayer.set(identifier, layer);
-    }
-    return identifier;
-}
-
-void InspectorLayerTreeAgent::unbind(const RenderLayer* layer)
-{
-    HashMap<const RenderLayer*, String>::iterator iterator = m_documentLayerToIdMap.find(layer);
-    if (iterator == m_documentLayerToIdMap.end())
-        return;
-    m_idToLayer.remove(iterator->value);
-    m_documentLayerToIdMap.remove(iterator);
-}
-
-String InspectorLayerTreeAgent::bindPseudoElement(PseudoElement* pseudoElement)
-{
-    if (!pseudoElement)
-        return emptyString();
-    String identifier = m_pseudoElementToIdMap.get(pseudoElement);
-    if (identifier.isNull()) {
-        identifier = IdentifiersFactory::createIdentifier();
-        m_pseudoElementToIdMap.set(pseudoElement, identifier);
-        m_idToPseudoElement.set(identifier, pseudoElement);
-    }
-    return identifier;
-}
-
-void InspectorLayerTreeAgent::unbindPseudoElement(PseudoElement* pseudoElement)
-{
-    HashMap<PseudoElement*, String>::iterator iterator = m_pseudoElementToIdMap.find(pseudoElement);
-    if (iterator == m_pseudoElementToIdMap.end())
-        return;
-    m_idToPseudoElement.remove(iterator->value);
-    m_pseudoElementToIdMap.remove(iterator);
-}
-
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.h b/Source/core/inspector/InspectorLayerTreeAgent.h
index 2f2e90c..5c82aff 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.h
+++ b/Source/core/inspector/InspectorLayerTreeAgent.h
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -40,59 +41,47 @@
 
 namespace WebCore {
 
+class InspectorDOMAgent;
 class InstrumentingAgents;
+class Page;
 
 typedef String ErrorString;
 
 class InspectorLayerTreeAgent : public InspectorBaseAgent<InspectorLayerTreeAgent>, public InspectorBackendDispatcher::LayerTreeCommandHandler {
 public:
-    static PassOwnPtr<InspectorLayerTreeAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
+    static PassOwnPtr<InspectorLayerTreeAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorDOMAgent* domAgent, Page* page)
     {
-        return adoptPtr(new InspectorLayerTreeAgent(instrumentingAgents, state));
+        return adoptPtr(new InspectorLayerTreeAgent(instrumentingAgents, state, domAgent, page));
     }
     ~InspectorLayerTreeAgent();
 
     virtual void setFrontend(InspectorFrontend*);
     virtual void clearFrontend();
     virtual void restore();
-    void reset();
 
     void didCommitLoad(Frame*, DocumentLoader*);
     void layerTreeDidChange();
-    void renderLayerDestroyed(const RenderLayer*);
-    void pseudoElementDestroyed(PseudoElement*);
 
     // Called from the front-end.
     virtual void enable(ErrorString*);
     virtual void disable(ErrorString*);
-    virtual void layersForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
-    virtual void reasonsForCompositingLayer(ErrorString*, const String& layerId, RefPtr<TypeBuilder::LayerTree::CompositingReasons>&);
+    virtual void getLayers(ErrorString*, const int* nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
 
 private:
-    InspectorLayerTreeAgent(InstrumentingAgents*, InspectorCompositeState*);
-
-    // RenderLayer-related methods.
-    String bind(const RenderLayer*);
-    void unbind(const RenderLayer*);
+    InspectorLayerTreeAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorDOMAgent*, Page*);
 
     void gatherLayersUsingRenderObjectHierarchy(ErrorString*, RenderObject*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
     void gatherLayersUsingRenderLayerHierarchy(ErrorString*, RenderLayer*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
-
-    PassRefPtr<TypeBuilder::LayerTree::Layer> buildObjectForLayer(ErrorString*, RenderLayer*);
-    PassRefPtr<TypeBuilder::LayerTree::IntRect> buildObjectForIntRect(const IntRect&);
+    void gatherLayersUsingGraphicsLayerHierarchy(ErrorString*, GraphicsLayer*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
+    void addRenderLayerBacking(ErrorString*, RenderLayerBacking*, Node*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
 
     int idForNode(ErrorString*, Node*);
 
-    String bindPseudoElement(PseudoElement*);
-    void unbindPseudoElement(PseudoElement*);
-
     InspectorFrontend::LayerTree* m_frontend;
+    Page* m_page;
+    InspectorDOMAgent* m_domAgent;
 
     HashMap<const RenderLayer*, String> m_documentLayerToIdMap;
-    HashMap<String, const RenderLayer*> m_idToLayer;
-
-    HashMap<PseudoElement*, String> m_pseudoElementToIdMap;
-    HashMap<String, PseudoElement*> m_idToPseudoElement;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorPageAgent.cpp b/Source/core/inspector/InspectorPageAgent.cpp
index d1d28f2..9a939cd 100644
--- a/Source/core/inspector/InspectorPageAgent.cpp
+++ b/Source/core/inspector/InspectorPageAgent.cpp
@@ -54,13 +54,13 @@
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
-#include "core/loader/cache/CachedFont.h"
-#include "core/loader/cache/CachedImage.h"
-#include "core/loader/cache/CachedScript.h"
+#include "core/loader/cache/CSSStyleSheetResource.h"
+#include "core/loader/cache/FontResource.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/MemoryCache.h"
 #include "core/loader/cache/Resource.h"
 #include "core/loader/cache/ResourceFetcher.h"
+#include "core/loader/cache/ScriptResource.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
@@ -195,14 +195,14 @@
     if (cachedResource) {
         switch (cachedResource->type()) {
         case Resource::CSSStyleSheet:
-            *result = static_cast<CachedCSSStyleSheet*>(cachedResource)->sheetText(false);
+            *result = static_cast<CSSStyleSheetResource*>(cachedResource)->sheetText(false);
             return true;
         case Resource::Script:
-            *result = static_cast<CachedScript*>(cachedResource)->script();
+            *result = static_cast<WebCore::ScriptResource*>(cachedResource)->script();
             return true;
         case Resource::MainResource:
             return false;
-        case Resource::RawResource: {
+        case Resource::Raw: {
             SharedBuffer* buffer = cachedResource->resourceBuffer();
             if (!buffer)
                 return false;
@@ -268,7 +268,7 @@
         return TypeBuilder::Page::ResourceType::Document;
     case ImageResource:
         return TypeBuilder::Page::ResourceType::Image;
-    case FontResource:
+    case Font:
         return TypeBuilder::Page::ResourceType::Font;
     case StylesheetResource:
         return TypeBuilder::Page::ResourceType::Stylesheet;
@@ -287,17 +287,17 @@
 InspectorPageAgent::ResourceType InspectorPageAgent::cachedResourceType(const Resource& cachedResource)
 {
     switch (cachedResource.type()) {
-    case Resource::ImageResource:
+    case Resource::Image:
         return InspectorPageAgent::ImageResource;
-    case Resource::FontResource:
-        return InspectorPageAgent::FontResource;
+    case Resource::Font:
+        return InspectorPageAgent::Font;
     case Resource::CSSStyleSheet:
         // Fall through.
     case Resource::XSLStyleSheet:
         return InspectorPageAgent::StylesheetResource;
     case Resource::Script:
         return InspectorPageAgent::ScriptResource;
-    case Resource::RawResource:
+    case Resource::Raw:
         return InspectorPageAgent::XHRResource;
     case Resource::MainResource:
         return InspectorPageAgent::DocumentResource;
@@ -494,14 +494,14 @@
         Resource* cachedResource = it->value.get();
 
         switch (cachedResource->type()) {
-        case Resource::ImageResource:
+        case Resource::Image:
             // Skip images that were not auto loaded (images disabled in the user agent).
-            if (static_cast<CachedImage*>(cachedResource)->stillNeedsLoad())
+            if (static_cast<ImageResource*>(cachedResource)->stillNeedsLoad())
                 continue;
             break;
-        case Resource::FontResource:
+        case Resource::Font:
             // Skip fonts that were referenced in CSS but never used/downloaded.
-            if (static_cast<CachedFont*>(cachedResource)->stillNeedsLoad())
+            if (static_cast<FontResource*>(cachedResource)->stillNeedsLoad())
                 continue;
             break;
         default:
@@ -900,8 +900,8 @@
 
 String InspectorPageAgent::resourceSourceMapURL(const String& url)
 {
-    DEFINE_STATIC_LOCAL(String, sourceMapHttpHeader, (ASCIILiteral("SourceMap")));
-    DEFINE_STATIC_LOCAL(String, deprecatedSourceMapHttpHeader, (ASCIILiteral("X-SourceMap")));
+    DEFINE_STATIC_LOCAL(String, sourceMapHttpHeader, ("SourceMap"));
+    DEFINE_STATIC_LOCAL(String, deprecatedSourceMapHttpHeader, ("X-SourceMap"));
     if (url.isEmpty())
         return String();
     Frame* frame = mainFrame();
diff --git a/Source/core/inspector/InspectorPageAgent.h b/Source/core/inspector/InspectorPageAgent.h
index b081dab..5b945f5 100644
--- a/Source/core/inspector/InspectorPageAgent.h
+++ b/Source/core/inspector/InspectorPageAgent.h
@@ -67,7 +67,7 @@
         DocumentResource,
         StylesheetResource,
         ImageResource,
-        FontResource,
+        Font,
         ScriptResource,
         XHRResource,
         WebSocketResource,
diff --git a/Source/core/inspector/InspectorProfilerAgent.cpp b/Source/core/inspector/InspectorProfilerAgent.cpp
index 92efc78..d0375e7 100644
--- a/Source/core/inspector/InspectorProfilerAgent.cpp
+++ b/Source/core/inspector/InspectorProfilerAgent.cpp
@@ -139,7 +139,7 @@
     if (incrementProfileNumber)
         m_currentUserInitiatedProfileNumber = m_nextUserInitiatedProfileNumber++;
 
-    return String(ASCIILiteral(userInitiatedProfileName)) + "." + String::number(m_currentUserInitiatedProfileNumber);
+    return String(userInitiatedProfileName) + "." + String::number(m_currentUserInitiatedProfileNumber);
 }
 
 void InspectorProfilerAgent::getProfileHeaders(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader> >& headers)
@@ -162,7 +162,9 @@
     }
     profileObject = TypeBuilder::Profiler::CPUProfile::create()
         .setHead(it->value->buildInspectorObjectForHead())
-        .setIdleTime(it->value->idleTime());
+        .setIdleTime(it->value->idleTime())
+        .setStartTime(it->value->startTime())
+        .setEndTime(it->value->endTime());
     profileObject->setSamples(it->value->buildInspectorObjectForSamples());
 }
 
diff --git a/Source/core/inspector/InspectorStyleSheet.cpp b/Source/core/inspector/InspectorStyleSheet.cpp
index 6e2f832..d0a81fe 100644
--- a/Source/core/inspector/InspectorStyleSheet.cpp
+++ b/Source/core/inspector/InspectorStyleSheet.cpp
@@ -551,7 +551,7 @@
 bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText, bool overwrite, String* oldText, ExceptionState& es)
 {
     ASSERT(m_parentStyleSheet);
-    DEFINE_STATIC_LOCAL(String, bogusPropertyName, (ASCIILiteral("-webkit-boguz-propertee")));
+    DEFINE_STATIC_LOCAL(String, bogusPropertyName, ("-webkit-boguz-propertee"));
 
     if (!m_parentStyleSheet->ensureParsedDataReady()) {
         es.throwDOMException(NotFoundError);
@@ -871,7 +871,7 @@
 
 NewLineAndWhitespace& InspectorStyle::newLineAndWhitespaceDelimiters() const
 {
-    DEFINE_STATIC_LOCAL(String, defaultPrefix, (ASCIILiteral("    ")));
+    DEFINE_STATIC_LOCAL(String, defaultPrefix, ("    "));
 
     if (m_formatAcquired)
         return m_format;
diff --git a/Source/core/inspector/InspectorTimelineAgent.cpp b/Source/core/inspector/InspectorTimelineAgent.cpp
index 61f8925..813b82e 100644
--- a/Source/core/inspector/InspectorTimelineAgent.cpp
+++ b/Source/core/inspector/InspectorTimelineAgent.cpp
@@ -153,7 +153,8 @@
 
 void TimelineTimeConverter::reset()
 {
-    m_startOffset = monotonicallyIncreasingTime() - currentTime();
+    m_startTimeMs = currentTime() * 1000;
+    m_timestampsBaseMs = monotonicallyIncreasingTime() * 1000;
 }
 
 void InspectorTimelineAgent::pushGCEventRecords()
@@ -164,9 +165,9 @@
     GCEvents events = m_gcEvents;
     m_gcEvents.clear();
     for (GCEvents::iterator i = events.begin(); i != events.end(); ++i) {
-        RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(m_timeConverter.fromMonotonicallyIncreasingTime(i->startTime), m_maxCallStackDepth, TimelineRecordType::GCEvent);
+        RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(m_timeConverter.toProtocolTimestamp(i->startTime), m_maxCallStackDepth, TimelineRecordType::GCEvent);
         record->setObject("data", TimelineRecordFactory::createGCEventData(i->collectedBytes));
-        record->setNumber("endTime", m_timeConverter.fromMonotonicallyIncreasingTime(i->endTime));
+        record->setNumber("endTime", m_timeConverter.toProtocolTimestamp(i->endTime));
         addRecordToTimeline(record.release());
     }
 }
@@ -218,6 +219,7 @@
     m_state->setBoolean(TimelineAgentState::includeDomCounters, includeDomCounters && *includeDomCounters);
     m_state->setBoolean(TimelineAgentState::includeNativeMemoryStatistics, includeNativeMemoryStatistics && *includeNativeMemoryStatistics);
     m_timeConverter.reset();
+    m_frontend->timelineStarted(m_timeConverter.timestampsBaseMs(), m_timeConverter.startTimeMs());
 
     m_instrumentingAgents->setInspectorTimelineAgent(this);
     ScriptGCEvent::addEventListener(this);
@@ -803,9 +805,9 @@
         m_domAgent->releaseBackendNodeIds(&unused, BackendNodeIdGroup);
 }
 
-double InspectorTimelineAgent::timestamp()
+double InspectorTimelineAgent::timestamp() const
 {
-    return m_timeConverter.fromMonotonicallyIncreasingTime(WTF::monotonicallyIncreasingTime());
+    return m_timeConverter.toProtocolTimestamp(WTF::monotonicallyIncreasingTime());
 }
 
 Page* InspectorTimelineAgent::page()
diff --git a/Source/core/inspector/InspectorTimelineAgent.h b/Source/core/inspector/InspectorTimelineAgent.h
index e18b2af..d43970e 100644
--- a/Source/core/inspector/InspectorTimelineAgent.h
+++ b/Source/core/inspector/InspectorTimelineAgent.h
@@ -86,14 +86,18 @@
 class TimelineTimeConverter {
 public:
     TimelineTimeConverter()
-        : m_startOffset(0)
+        : m_timestampsBaseMs(0)
+        , m_startTimeMs(0)
     {
     }
-    double fromMonotonicallyIncreasingTime(double time) const  { return (time - m_startOffset) * 1000.0; }
+    double toProtocolTimestamp(double seconds) const  { return seconds * 1000.0 - m_timestampsBaseMs; }
+    double startTimeMs() const { return m_startTimeMs; }
+    double timestampsBaseMs() const { return m_timestampsBaseMs; }
     void reset();
 
 private:
-    double m_startOffset;
+    double m_timestampsBaseMs;
+    double m_startTimeMs;
 };
 
 class InspectorTimelineAgent
@@ -252,7 +256,7 @@
     long long idForNode(Node*);
     void releaseNodeIds();
 
-    double timestamp();
+    double timestamp() const;
     Page* page();
 
     InspectorPageAgent* m_pageAgent;
diff --git a/Source/core/inspector/ScriptProfile.cpp b/Source/core/inspector/ScriptProfile.cpp
index ca8a4a2..513586b 100644
--- a/Source/core/inspector/ScriptProfile.cpp
+++ b/Source/core/inspector/ScriptProfile.cpp
@@ -59,6 +59,16 @@
     return m_idleTime;
 }
 
+double ScriptProfile::startTime() const
+{
+    return static_cast<double>(m_profile->GetStartTime()) / 1000000;
+}
+
+double ScriptProfile::endTime() const
+{
+    return static_cast<double>(m_profile->GetEndTime()) / 1000000;
+}
+
 static PassRefPtr<TypeBuilder::Profiler::CPUProfileNode> buildInspectorObjectFor(const v8::CpuProfileNode* node)
 {
     v8::HandleScope handleScope;
@@ -75,8 +85,7 @@
         .setScriptId(String::number(node->GetScriptId()))
         .setUrl(toWebCoreString(node->GetScriptResourceName()))
         .setLineNumber(node->GetLineNumber())
-        .setTotalTime(node->GetTotalTime())
-        .setSelfTime(node->GetSelfTime())
+        .setHitCount(node->GetSelfSamplesCount())
         .setCallUID(node->GetCallUid())
         .setChildren(children.release());
     result->setId(node->GetNodeId());
diff --git a/Source/core/inspector/ScriptProfile.h b/Source/core/inspector/ScriptProfile.h
index 19afeac..ba14b98 100644
--- a/Source/core/inspector/ScriptProfile.h
+++ b/Source/core/inspector/ScriptProfile.h
@@ -53,6 +53,9 @@
     unsigned int uid() const;
     double idleTime() const;
 
+    double startTime() const;
+    double endTime() const;
+
     PassRefPtr<TypeBuilder::Profiler::CPUProfileNode> buildInspectorObjectForHead() const;
     PassRefPtr<TypeBuilder::Array<int> > buildInspectorObjectForSamples() const;
 
diff --git a/Source/core/inspector/TimelineTraceEventProcessor.cpp b/Source/core/inspector/TimelineTraceEventProcessor.cpp
index ba28720..c6537c1 100644
--- a/Source/core/inspector/TimelineTraceEventProcessor.cpp
+++ b/Source/core/inspector/TimelineTraceEventProcessor.cpp
@@ -266,13 +266,13 @@
 void TimelineTraceEventProcessor::onPaintSetupBegin(const TraceEvent& event)
 {
     ASSERT(!m_paintSetupStart);
-    m_paintSetupStart = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
+    m_paintSetupStart = m_timeConverter.toProtocolTimestamp(event.timestamp());
 }
 
 void TimelineTraceEventProcessor::onPaintSetupEnd(const TraceEvent& event)
 {
     ASSERT(m_paintSetupStart);
-    m_paintSetupEnd = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
+    m_paintSetupEnd = m_timeConverter.toProtocolTimestamp(event.timestamp());
 }
 
 void TimelineTraceEventProcessor::onRasterTaskBegin(const TraceEvent& event)
@@ -293,7 +293,7 @@
     if (!state.inKnownLayerTask)
         return;
     ASSERT(state.recordStack.isOpenRecordOfType(TimelineRecordType::Rasterize));
-    state.recordStack.closeScopedRecord(m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp()));
+    state.recordStack.closeScopedRecord(m_timeConverter.toProtocolTimestamp(event.timestamp()));
     leaveLayerTask(state);
 }
 
@@ -336,7 +336,7 @@
     if (!state.inKnownLayerTask)
         return;
     ASSERT(state.recordStack.isOpenRecordOfType(TimelineRecordType::DecodeImage));
-    state.recordStack.closeScopedRecord(m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp()));
+    state.recordStack.closeScopedRecord(m_timeConverter.toProtocolTimestamp(event.timestamp()));
 }
 
 void TimelineTraceEventProcessor::onLayerDeleted(const TraceEvent& event)
@@ -370,7 +370,7 @@
 
 PassRefPtr<JSONObject> TimelineTraceEventProcessor::createRecord(const TraceEvent& event, const String& recordType, PassRefPtr<JSONObject> data)
 {
-    double startTime = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
+    double startTime = m_timeConverter.toProtocolTimestamp(event.timestamp());
     RefPtr<JSONObject> record = TimelineRecordFactory::createBackgroundRecord(startTime, String::number(event.threadIdentifier()));
     record->setString("type", recordType);
     record->setObject("data", data ? data : JSONObject::create());
diff --git a/Source/core/loader/DocumentLoader.cpp b/Source/core/loader/DocumentLoader.cpp
index 5d64a09..bb5a318 100644
--- a/Source/core/loader/DocumentLoader.cpp
+++ b/Source/core/loader/DocumentLoader.cpp
@@ -101,7 +101,6 @@
     , m_isStopping(false)
     , m_isClientRedirect(false)
     , m_replacesCurrentHistoryItem(false)
-    , m_wasOnloadHandled(false)
     , m_loadingMainResource(false)
     , m_timeOfLastDataReceived(0.0)
     , m_identifierForLoadWithoutResourceLoader(0)
@@ -378,10 +377,7 @@
 void DocumentLoader::handleSubstituteDataLoadNow(DocumentLoaderTimer*)
 {
     RefPtr<DocumentLoader> protect(this);
-    KURL url = m_substituteData.responseURL();
-    if (url.isEmpty())
-        url = m_request.url();
-    ResourceResponse response(url, m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
+    ResourceResponse response(m_request.url(), m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
     responseReceived(0, response);
     if (isStopping())
         return;
@@ -406,35 +402,22 @@
 
 bool DocumentLoader::shouldContinueForNavigationPolicy(const ResourceRequest& request, PolicyCheckLoadType policyCheckLoadType)
 {
-    NavigationAction action = triggeringAction();
-    if (action.isEmpty()) {
-        action = NavigationAction(request, NavigationTypeOther);
-        setTriggeringAction(action);
-    }
-
     // Don't ask if we are loading an empty URL.
-    if (!request.isNull() && request.url().isEmpty())
+    if (request.url().isEmpty())
         return true;
 
-    // We are always willing to show alternate content for unreachable URLs;
-    // treat it like a reload so it maintains the right state for b/f list.
-    if (m_substituteData.isValid() && !m_substituteData.failingURL().isEmpty()) {
-        if (isBackForwardLoadType(frameLoader()->loadType()))
-            frameLoader()->setLoadType(FrameLoadTypeReload);
+    // We are always willing to show alternate content for unreachable URLs.
+    if (m_substituteData.isValid() && !m_substituteData.failingURL().isEmpty())
         return true;
-    }
 
     // If we're loading content into a subframe, check against the parent's Content Security Policy
     // and kill the load if that check fails.
     if (m_frame->ownerElement() && !m_frame->ownerElement()->document()->contentSecurityPolicy()->allowChildFrameFromSource(request.url()))
         return false;
 
-    if (request.isNull())
-        return false;
-
     NavigationPolicy policy = NavigationPolicyCurrentTab;
-    action.specifiesNavigationPolicy(&policy);
-    policy = frameLoader()->client()->decidePolicyForNavigation(request, action.type(), policy, policyCheckLoadType == PolicyCheckRedirect);
+    m_triggeringAction.specifiesNavigationPolicy(&policy);
+    policy = frameLoader()->client()->decidePolicyForNavigation(request, m_triggeringAction.type(), policy, policyCheckLoadType == PolicyCheckRedirect);
     if (policy == NavigationPolicyCurrentTab)
         return true;
     if (policy == NavigationPolicyIgnore)
@@ -629,7 +612,7 @@
 
     String encoding = overrideEncoding().isNull() ? response().textEncodingName().impl() : overrideEncoding();
     bool userChosen = !overrideEncoding().isNull();
-    m_writer = createWriterFor(m_frame, 0, documentURL(), mimeType, encoding, false, false);
+    m_writer = createWriterFor(m_frame, 0, requestURL(), mimeType, encoding, false, false);
     m_writer->setDocumentWasLoadedAsPartOfNavigation();
     // This should be set before receivedFirstData().
     if (!overridingURL.isEmpty())
@@ -637,6 +620,7 @@
 
     // Call receivedFirstData() exactly once per load.
     frameLoader()->receivedFirstData();
+    m_frame->document()->maybeHandleHttpRefresh(m_response.httpHeaderField("Refresh"), Document::HttpRefreshFromHeader);
 }
 
 void DocumentLoader::commitData(const char* bytes, size_t length)
@@ -853,16 +837,6 @@
     return request().url();
 }
 
-KURL DocumentLoader::documentURL() const
-{
-    KURL url = substituteData().responseURL();
-    if (url.isEmpty())
-        url = requestURL();
-    if (url.isEmpty())
-        url = m_response.url();
-    return url;
-}
-
 const String& DocumentLoader::responseMIMEType() const
 {
     return m_response.mimeType();
@@ -928,6 +902,7 @@
 
 void DocumentLoader::startLoadingMainResource()
 {
+    RefPtr<DocumentLoader> protect(this);
     m_mainDocumentError = ResourceError();
     timing()->markNavigationStart();
     ASSERT(!m_mainResource);
@@ -1003,12 +978,6 @@
         frame->loader()->checkLoadComplete();
 }
 
-void DocumentLoader::handledOnloadEvents()
-{
-    m_wasOnloadHandled = true;
-    applicationCacheHost()->stopDeferringEvents();
-}
-
 DocumentWriter* DocumentLoader::beginWriting(const String& mimeType, const String& encoding, const KURL& url)
 {
     m_writer = createWriterFor(m_frame, 0, url, mimeType, encoding, false, true);
diff --git a/Source/core/loader/DocumentLoader.h b/Source/core/loader/DocumentLoader.h
index e8c9df4..112292e 100644
--- a/Source/core/loader/DocumentLoader.h
+++ b/Source/core/loader/DocumentLoader.h
@@ -35,7 +35,7 @@
 #include "core/loader/NavigationAction.h"
 #include "core/loader/ResourceLoaderOptions.h"
 #include "core/loader/SubstituteData.h"
-#include "core/loader/cache/CachedRawResource.h"
+#include "core/loader/cache/RawResource.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "core/platform/network/ResourceError.h"
@@ -65,7 +65,7 @@
 
     typedef HashSet<RefPtr<ResourceLoader> > ResourceLoaderSet;
 
-    class DocumentLoader : public RefCounted<DocumentLoader>, private CachedRawResourceClient {
+    class DocumentLoader : public RefCounted<DocumentLoader>, private RawResourceClient {
         WTF_MAKE_FAST_ALLOCATED;
     public:
         static PassRefPtr<DocumentLoader> create(const ResourceRequest& request, const SubstituteData& data)
@@ -119,8 +119,6 @@
         void setIsClientRedirect(bool isClientRedirect) { m_isClientRedirect = isClientRedirect; }
         bool replacesCurrentHistoryItem() const { return m_replacesCurrentHistoryItem; }
         void setReplacesCurrentHistoryItem(bool replacesCurrentHistoryItem) { m_replacesCurrentHistoryItem = replacesCurrentHistoryItem; }
-        void handledOnloadEvents();
-        bool wasOnloadHandled() { return m_wasOnloadHandled; }
         bool isLoadingInAPISense() const;
         void setTitle(const StringWithDirection&);
         const String& overrideEncoding() const { return m_overrideEncoding; }
@@ -179,8 +177,6 @@
         void ensureWriter();
         void ensureWriter(const String& mimeType, const KURL& overridingURL = KURL());
 
-        // The URL of the document resulting from this DocumentLoader.
-        KURL documentURL() const;
         Document* document() const;
 
         void setRequest(const ResourceRequest&);
@@ -223,7 +219,7 @@
         Frame* m_frame;
         RefPtr<ResourceFetcher> m_fetcher;
 
-        ResourcePtr<CachedRawResource> m_mainResource;
+        ResourcePtr<RawResource> m_mainResource;
         ResourceLoaderSet m_resourceLoaders;
         ResourceLoaderSet m_multipartResourceLoaders;
 
@@ -255,10 +251,6 @@
         bool m_isClientRedirect;
         bool m_replacesCurrentHistoryItem;
 
-        // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadHandled are roughly the same
-        // and should be merged.
-        bool m_wasOnloadHandled;
-
         StringWithDirection m_pageTitle;
 
         String m_overrideEncoding;
diff --git a/Source/core/loader/DocumentThreadableLoader.cpp b/Source/core/loader/DocumentThreadableLoader.cpp
index 5471fdb..f7e0544 100644
--- a/Source/core/loader/DocumentThreadableLoader.cpp
+++ b/Source/core/loader/DocumentThreadableLoader.cpp
@@ -39,8 +39,8 @@
 #include "core/loader/DocumentThreadableLoaderClient.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/ThreadableLoaderClient.h"
-#include "core/loader/cache/CachedRawResource.h"
 #include "core/loader/cache/FetchRequest.h"
+#include "core/loader/cache/RawResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/Frame.h"
@@ -177,7 +177,7 @@
     // which could lead to calling Resource::removeClient() multiple times for
     // this DocumentThreadableLoader. Save off a copy of m_resource and clear it to
     // prevent the reentrancy.
-    if (ResourcePtr<CachedRawResource> resource = m_resource) {
+    if (ResourcePtr<RawResource> resource = m_resource) {
         m_resource = 0;
         resource->removeClient(this);
     }
diff --git a/Source/core/loader/DocumentThreadableLoader.h b/Source/core/loader/DocumentThreadableLoader.h
index d487201..06e85eb 100644
--- a/Source/core/loader/DocumentThreadableLoader.h
+++ b/Source/core/loader/DocumentThreadableLoader.h
@@ -33,7 +33,7 @@
 #define DocumentThreadableLoader_h
 
 #include "core/loader/ThreadableLoader.h"
-#include "core/loader/cache/CachedRawResource.h"
+#include "core/loader/cache/RawResource.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "core/platform/network/ResourceError.h"
@@ -50,7 +50,7 @@
     class SecurityOrigin;
     class ThreadableLoaderClient;
 
-    class DocumentThreadableLoader : public RefCounted<DocumentThreadableLoader>, public ThreadableLoader, private CachedRawResourceClient  {
+    class DocumentThreadableLoader : public RefCounted<DocumentThreadableLoader>, public ThreadableLoader, private RawResourceClient  {
         WTF_MAKE_FAST_ALLOCATED;
     public:
         static void loadResourceSynchronously(Document*, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&);
@@ -77,7 +77,7 @@
 
         void clearResource();
 
-        // CachedRawResourceClient
+        // RawResourceClient
         virtual void dataSent(Resource*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
         virtual void responseReceived(Resource*, const ResourceResponse&);
         virtual void dataReceived(Resource*, const char* data, int dataLength);
@@ -103,7 +103,7 @@
 
         SecurityOrigin* securityOrigin() const;
 
-        ResourcePtr<CachedRawResource> m_resource;
+        ResourcePtr<RawResource> m_resource;
         ThreadableLoaderClient* m_client;
         Document* m_document;
         ThreadableLoaderOptions m_options;
diff --git a/Source/core/loader/EmptyClients.h b/Source/core/loader/EmptyClients.h
index 4400cb1..09da78f 100644
--- a/Source/core/loader/EmptyClients.h
+++ b/Source/core/loader/EmptyClients.h
@@ -196,7 +196,6 @@
 
     virtual void dispatchDidHandleOnloadEvents() OVERRIDE { }
     virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() OVERRIDE { }
-    virtual void dispatchDidChangeLocationWithinPage() OVERRIDE { }
     virtual void dispatchWillClose() OVERRIDE { }
     virtual void dispatchDidStartProvisionalLoad() OVERRIDE { }
     virtual void dispatchDidReceiveTitle(const StringWithDirection&) OVERRIDE { }
diff --git a/Source/core/loader/FrameLoader.cpp b/Source/core/loader/FrameLoader.cpp
index f0ef80e..1cfc5ca 100644
--- a/Source/core/loader/FrameLoader.cpp
+++ b/Source/core/loader/FrameLoader.cpp
@@ -160,8 +160,6 @@
     , m_state(FrameStateProvisional)
     , m_loadType(FrameLoadTypeStandard)
     , m_inStopAllLoaders(false)
-    , m_didCallImplicitClose(true)
-    , m_wasUnloadEventEmitted(false)
     , m_pageDismissalEventBeingDispatched(NoDismissal)
     , m_isComplete(false)
     , m_containsPlugins(false)
@@ -288,7 +286,8 @@
 
     if (unloadEventPolicy != UnloadEventPolicyNone) {
         if (m_frame->document()) {
-            if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
+            if (m_frame->document()->unloadEventStillNeeded()) {
+                m_frame->document()->unloadEventStarted();
                 Element* currentFocusedElement = m_frame->document()->focusedElement();
                 if (currentFocusedElement && currentFocusedElement->hasTagName(inputTag))
                     toHTMLInputElement(currentFocusedElement)->endEditing();
@@ -314,9 +313,10 @@
                     }
                 }
                 m_pageDismissalEventBeingDispatched = NoDismissal;
-                if (m_frame->document())
+                if (m_frame->document()) {
                     m_frame->document()->updateStyleIfNeeded();
-                m_wasUnloadEventEmitted = true;
+                    m_frame->document()->unloadEventWasHandled();
+                }
             }
         }
 
@@ -332,7 +332,6 @@
     }
 
     m_isComplete = true; // to avoid calling completed() in finishedParsing()
-    m_didCallImplicitClose = true; // don't want that one either
 
     if (m_frame->document() && m_frame->document()->parsing()) {
         finishedParsing();
@@ -379,7 +378,6 @@
 void FrameLoader::didExplicitOpen()
 {
     m_isComplete = false;
-    m_didCallImplicitClose = false;
 
     // Calling document.open counts as committing the first real document load.
     if (!m_stateMachine.committedFirstRealDocumentLoad())
@@ -465,27 +463,6 @@
         if (!ptitle.isNull())
             m_client->dispatchDidReceiveTitle(ptitle);
     }
-
-    if (!m_documentLoader)
-        return;
-    if (m_frame->document()->isViewSource())
-        return;
-
-    double delay;
-    String url;
-    if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, url))
-        return;
-    if (url.isEmpty())
-        url = m_frame->document()->url().string();
-    else
-        url = m_frame->document()->completeURL(url).string();
-
-    if (!protocolIsJavaScript(url)) {
-        m_frame->navigationScheduler()->scheduleRedirect(delay, url);
-    } else {
-        String message = "Refused to refresh " + m_frame->document()->url().elidedString() + " to a javascript: URL";
-        m_frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
-    }
 }
 
 void FrameLoader::setOutgoingReferrer(const KURL& url)
@@ -497,7 +474,6 @@
 {
     m_needsClear = true;
     m_isComplete = false;
-    m_didCallImplicitClose = false;
     m_frame->document()->setReadyState(Document::Loading);
 
     if (history()->currentItem() && m_loadType == FrameLoadTypeBackForward)
@@ -610,8 +586,8 @@
     m_isComplete = true;
     m_requestedHistoryItem = 0;
     m_frame->document()->setReadyState(Document::Complete);
-
-    checkCallImplicitClose(); // if we didn't do it before
+    if (m_frame->document()->loadEventStillNeeded())
+        m_frame->document()->implicitClose();
 
     m_frame->navigationScheduler()->startTimer();
 
@@ -658,19 +634,6 @@
     startCheckCompleteTimer();
 }
 
-void FrameLoader::checkCallImplicitClose()
-{
-    if (m_didCallImplicitClose || m_frame->document()->parsing() || m_frame->document()->isDelayingLoadEvent())
-        return;
-
-    if (!allChildrenAreComplete())
-        return; // still got a frame running -> too early
-
-    m_didCallImplicitClose = true;
-    m_wasUnloadEventEmitted = false;
-    m_frame->document()->implicitClose();
-}
-
 String FrameLoader::outgoingReferrer() const
 {
     // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
@@ -741,38 +704,56 @@
     m_submittedFormURL = KURL();
 }
 
+void FrameLoader::updateForSameDocumentNavigation(const KURL& newURL, SameDocumentNavigationSource sameDocumentNavigationSource, PassRefPtr<SerializedScriptValue> data, const String& title)
+{
+    // Update the data source's request with the new URL to fake the URL change
+    KURL oldURL = m_frame->document()->url();
+    m_frame->document()->setURL(newURL);
+    setOutgoingReferrer(newURL);
+    documentLoader()->replaceRequestURLForSameDocumentNavigation(newURL);
+
+    if (sameDocumentNavigationSource == SameDocumentNavigationDefault)
+        history()->updateForSameDocumentNavigation();
+    else if (sameDocumentNavigationSource == SameDocumentNavigationPushState)
+        history()->pushState(data, title, newURL.string());
+    else if (sameDocumentNavigationSource == SameDocumentNavigationReplaceState)
+        history()->replaceState(data, title, newURL.string());
+    else
+        ASSERT_NOT_REACHED();
+
+    // Generate start and stop notifications only when loader is completed so that we
+    // don't fire them for fragment redirection that happens in window.onload handler.
+    // See https://bugs.webkit.org/show_bug.cgi?id=31838
+    if (m_frame->document()->loadEventFinished())
+        m_client->postProgressStartedNotification();
+
+    m_documentLoader->clearRedirectChain();
+    if (m_documentLoader->isClientRedirect())
+        m_documentLoader->appendRedirect(oldURL);
+    m_documentLoader->appendRedirect(newURL);
+
+    m_client->dispatchDidNavigateWithinPage();
+
+    if (m_frame->document()->loadEventFinished())
+        m_client->postProgressFinishedNotification();
+}
+
 void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation)
 {
     // If we have a state object, we cannot also be a new navigation.
     ASSERT(!stateObject || (stateObject && !isNewNavigation));
 
-    // Update the data source's request with the new URL to fake the URL change
     KURL oldURL = m_frame->document()->url();
-    m_frame->document()->setURL(url);
-    setOutgoingReferrer(url);
-    documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
-    if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
-        // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add
-        // based on the current request. Must also happen before we openURL and displace the
-        // scroll position, since adding the BF item will save away scroll state.
-
-        // NB2: If we were loading a long, slow doc, and the user fragment navigated before
-        // it was done, currItem is now set the that slow doc, and prevItem is whatever was
-        // before it.  Adding the b/f item will bump the slow doc down to prevItem, even
-        // though its load is not yet done.  I think this all works out OK, for one because
-        // we have already saved away the scroll and doc state for the long slow load,
-        // but it's not an obvious case.
-
-        history()->updateBackForwardListForFragmentScroll();
+    // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
+    bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
+    if (hashChange) {
+        m_frame->eventHandler()->stopAutoscrollTimer();
+        m_frame->document()->enqueueHashchangeEvent(oldURL, url);
     }
 
-    bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
-
-    history()->updateForSameDocumentNavigation();
-
-    // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
-    if (hashChange)
-        m_frame->eventHandler()->stopAutoscrollTimer();
+    m_documentLoader->setIsClientRedirect((m_startingClientRedirect && !isNewNavigation) || !UserGestureIndicator::processingUserGesture());
+    m_documentLoader->setReplacesCurrentHistoryItem(!isNewNavigation);
+    updateForSameDocumentNavigation(url, SameDocumentNavigationDefault, 0, String());
 
     // It's important to model this as a load that starts and immediately finishes.
     // Otherwise, the parent frame may think we never finished loading.
@@ -785,30 +766,7 @@
     m_isComplete = false;
     checkCompleted();
 
-    // Generate start and stop notifications only when loader is completed so that we
-    // don't fire them for fragment redirection that happens in window.onload handler.
-    // See https://bugs.webkit.org/show_bug.cgi?id=31838
-    if (m_documentLoader->wasOnloadHandled())
-        m_client->postProgressStartedNotification();
-
-    m_documentLoader->clearRedirectChain();
-    m_documentLoader->setIsClientRedirect((m_startingClientRedirect && !isNewNavigation) || !UserGestureIndicator::processingUserGesture());
-    m_documentLoader->setReplacesCurrentHistoryItem(!isNewNavigation);
-    if (m_documentLoader->isClientRedirect())
-        m_documentLoader->appendRedirect(oldURL);
-    m_documentLoader->appendRedirect(url);
-
-    m_client->dispatchDidNavigateWithinPage();
-
-    if (m_documentLoader->wasOnloadHandled())
-        m_client->postProgressFinishedNotification();
-
     m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
-
-    if (hashChange) {
-        m_frame->document()->enqueueHashchangeEvent(oldURL, url);
-        m_client->dispatchDidChangeLocationWithinPage();
-    }
 }
 
 bool FrameLoader::isComplete() const
@@ -977,32 +935,6 @@
     return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), "text/html", "UTF-8", KURL());
 }
 
-void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, FrameLoadType type, PassRefPtr<FormState> formState, const SubstituteData& substituteData, const String& overrideEncoding)
-{
-    ASSERT(m_client->hasWebView());
-    if (m_pageDismissalEventBeingDispatched != NoDismissal)
-        return;
-
-    if (!m_stateMachine.startedFirstRealLoad())
-        m_stateMachine.advanceTo(FrameLoaderStateMachine::StartedFirstRealLoad);
-
-    RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, substituteData.isValid() ? substituteData : defaultSubstituteDataForURL(request.url()));
-    loader->setTriggeringAction(action);
-
-    if (Frame* parent = m_frame->tree()->parent())
-        loader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
-    else if (!overrideEncoding.isEmpty())
-        loader->setOverrideEncoding(overrideEncoding);
-    else if (m_documentLoader)
-        loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
-
-    loader->setReplacesCurrentHistoryItem(type == FrameLoadTypeRedirectWithLockedBackForwardList);
-    loader->setIsClientRedirect(m_startingClientRedirect);
-    m_policyDocumentLoader = loader;
-    m_policyDocumentLoader->setFrame(m_frame);
-    checkNavigationPolicyAndContinueLoad(formState, type);
-}
-
 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
 {
     ASSERT(!url.isEmpty());
@@ -1189,7 +1121,6 @@
         window->setStatus(String());
         window->setDefaultStatus(String());
     }
-    m_didCallImplicitClose = false;
     started();
 }
 
@@ -1376,14 +1307,6 @@
     return userAgent;
 }
 
-void FrameLoader::handledOnloadEvents()
-{
-    m_client->dispatchDidHandleOnloadEvents();
-
-    if (documentLoader())
-        documentLoader()->handledOnloadEvents();
-}
-
 void FrameLoader::frameDetached()
 {
     // stopAllLoaders can detach the Frame, so protect it.
@@ -1570,6 +1493,8 @@
             m_provisionalDocumentLoader->detachFromFrame();
         m_provisionalDocumentLoader = 0;
     }
+    if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(request.url()))
+        history()->updateBackForwardListForFragmentScroll();
     loadInSameDocument(request.url(), 0, isNewNavigation);
 }
 
@@ -1674,49 +1599,40 @@
     return false;
 }
 
-void FrameLoader::checkNavigationPolicyAndContinueLoad(PassRefPtr<FormState> formState, FrameLoadType type)
+void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, FrameLoadType type, PassRefPtr<FormState> formState, const SubstituteData& substituteData, const String& overrideEncoding)
 {
-    // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
-    // nil policyDataSource because loading the alternate page will have passed
-    // through this method already, nested; otherwise, policyDataSource should still be set.
-    ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
+    ASSERT(m_client->hasWebView());
+    if (m_pageDismissalEventBeingDispatched != NoDismissal)
+        return;
+
+    // We skip dispatching the beforeload event on the frame owner if we've already committed a real
+    // document load because the event would leak subsequent activity by the frame which the parent
+    // frame isn't supposed to learn. For example, if the child frame navigated to  a new URL, the
+    // parent frame shouldn't learn the URL.
+    if (!m_stateMachine.committedFirstRealDocumentLoad() && m_frame->ownerElement() && !m_frame->ownerElement()->dispatchBeforeLoadEvent(request.url().string()))
+        return;
+
+    if (!m_stateMachine.startedFirstRealLoad())
+        m_stateMachine.advanceTo(FrameLoaderStateMachine::StartedFirstRealLoad);
+
+    m_policyDocumentLoader = m_client->createDocumentLoader(request, substituteData.isValid() ? substituteData : defaultSubstituteDataForURL(request.url()));
+    m_policyDocumentLoader->setFrame(m_frame);
+    m_policyDocumentLoader->setTriggeringAction(action);
+    m_policyDocumentLoader->setReplacesCurrentHistoryItem(type == FrameLoadTypeRedirectWithLockedBackForwardList);
+    m_policyDocumentLoader->setIsClientRedirect(m_startingClientRedirect);
+
+    if (Frame* parent = m_frame->tree()->parent())
+        m_policyDocumentLoader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
+    else if (!overrideEncoding.isEmpty())
+        m_policyDocumentLoader->setOverrideEncoding(overrideEncoding);
+    else if (m_documentLoader)
+        m_policyDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
 
     // stopAllLoaders can detach the Frame, so protect it.
     RefPtr<Frame> protect(m_frame);
-
-    bool isTargetItem = history()->provisionalItem() ? history()->provisionalItem()->isTargetItem() : false;
-
-    bool shouldContinue = false;
-    if (m_stateMachine.committedFirstRealDocumentLoad() || !m_frame->ownerElement()
-        || m_frame->ownerElement()->dispatchBeforeLoadEvent(m_policyDocumentLoader->request().url().string())) {
-        // We skip dispatching the beforeload event if we've already
-        // committed a real document load because the event would leak
-        // subsequent activity by the frame which the parent frame isn't
-        // supposed to learn. For example, if the child frame navigated to
-        // a new URL, the parent frame shouldn't learn the URL.
-        shouldContinue = m_policyDocumentLoader->shouldContinueForNavigationPolicy(m_policyDocumentLoader->request(), DocumentLoader::PolicyCheckStandard);
-    }
-
-    // Two reasons we can't continue:
-    //    1) Navigation policy delegate said we can't so request is nil. A primary case of this
-    //       is the user responding Cancel to the form repost nag sheet.
-    //    2) User responded Cancel to an alert popped up by the before unload event handler.
-    bool canContinue = shouldContinue && shouldClose();
-
-    if (!canContinue) {
+    if (!m_policyDocumentLoader->shouldContinueForNavigationPolicy(request, DocumentLoader::PolicyCheckStandard) || !shouldClose()) {
         m_policyDocumentLoader->detachFromFrame();
         m_policyDocumentLoader = 0;
-
-        // If the navigation request came from the back/forward menu, and we punt on it, we have the
-        // problem that we have optimistically moved the b/f cursor already, so move it back.  For sanity,
-        // we only do this when punting a navigation for the target frame or top-level frame.
-        if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(type)) {
-            if (Page* page = m_frame->page()) {
-                Frame* mainFrame = page->mainFrame();
-                if (HistoryItem* resetItem = mainFrame->loader()->history()->currentItem())
-                    page->backForward()->setCurrentItem(resetItem);
-            }
-        }
         return;
     }
 
@@ -1728,10 +1644,8 @@
     if (!m_frame->page())
         return;
 
-    if (Page* page = m_frame->page()) {
-        if (page->mainFrame() == m_frame)
-            m_frame->page()->inspectorController()->resume();
-    }
+    if (isLoadingMainFrame())
+        m_frame->page()->inspectorController()->resume();
     m_frame->navigationScheduler()->cancel();
 
     m_provisionalDocumentLoader = m_policyDocumentLoader.release();
diff --git a/Source/core/loader/FrameLoader.h b/Source/core/loader/FrameLoader.h
index ff48106..9fb2527 100644
--- a/Source/core/loader/FrameLoader.h
+++ b/Source/core/loader/FrameLoader.h
@@ -174,7 +174,6 @@
 
     void receivedFirstData();
 
-    void handledOnloadEvents();
     String userAgent(const KURL&) const;
 
     void dispatchDidClearWindowObjectInWorld(DOMWrapperWorld*);
@@ -193,8 +192,6 @@
 
     void resetMultipleFormSubmissionProtection();
 
-    void checkCallImplicitClose();
-
     void frameDetached();
 
     void setOutgoingReferrer(const KURL&);
@@ -238,6 +235,8 @@
     };
     PageDismissalType pageDismissalEventBeingDispatched() const { return m_pageDismissalEventBeingDispatched; }
 
+    void updateForSameDocumentNavigation(const KURL&, SameDocumentNavigationSource, PassRefPtr<SerializedScriptValue>, const String& title);
+
 private:
     bool allChildrenAreComplete() const; // immediate children, not all descendants
 
@@ -258,7 +257,6 @@
     void didAllowNavigationViaBeforeUnloadConfirmationPanel() { m_hasAllowedNavigationViaBeforeUnloadConfirmationPanel = true; }
     void clearAllowNavigationViaBeforeUnloadConfirmationPanel() { m_hasAllowedNavigationViaBeforeUnloadConfirmationPanel = false; }
 
-    void checkNavigationPolicyAndContinueLoad(PassRefPtr<FormState>, FrameLoadType);
     void checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction&, bool isNewNavigation);
     void checkNewWindowPolicyAndContinue(PassRefPtr<FormState>, const String& frameName, const NavigationAction&);
 
@@ -318,8 +316,6 @@
 
     String m_outgoingReferrer;
 
-    bool m_didCallImplicitClose;
-    bool m_wasUnloadEventEmitted;
     PageDismissalType m_pageDismissalEventBeingDispatched;
     bool m_isComplete;
 
diff --git a/Source/core/loader/FrameLoaderClient.h b/Source/core/loader/FrameLoaderClient.h
index e72d790..f02a306 100644
--- a/Source/core/loader/FrameLoaderClient.h
+++ b/Source/core/loader/FrameLoaderClient.h
@@ -102,7 +102,6 @@
         virtual void dispatchDidHandleOnloadEvents() = 0;
         virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() = 0;
         virtual void dispatchDidNavigateWithinPage() { }
-        virtual void dispatchDidChangeLocationWithinPage() = 0;
         virtual void dispatchWillClose() = 0;
         virtual void dispatchDidStartProvisionalLoad() = 0;
         virtual void dispatchDidReceiveTitle(const StringWithDirection&) = 0;
diff --git a/Source/core/loader/FrameLoaderTypes.h b/Source/core/loader/FrameLoaderTypes.h
index 25c7a65..a7444ba 100644
--- a/Source/core/loader/FrameLoaderTypes.h
+++ b/Source/core/loader/FrameLoaderTypes.h
@@ -92,6 +92,11 @@
         EndToEndReload
     };
 
+    enum SameDocumentNavigationSource {
+        SameDocumentNavigationDefault,
+        SameDocumentNavigationPushState,
+        SameDocumentNavigationReplaceState
+    };
 }
 
 #endif
diff --git a/Source/core/loader/ImageLoader.cpp b/Source/core/loader/ImageLoader.cpp
index ec0ed7b..668cb97 100644
--- a/Source/core/loader/ImageLoader.cpp
+++ b/Source/core/loader/ImageLoader.cpp
@@ -30,8 +30,8 @@
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/loader/CrossOriginAccessControl.h"
-#include "core/loader/cache/CachedImage.h"
 #include "core/loader/cache/FetchRequest.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/Frame.h"
 #include "core/rendering/RenderImage.h"
@@ -102,7 +102,7 @@
         m_element->deref();
 }
 
-void ImageLoader::setImage(CachedImage* newImage)
+void ImageLoader::setImage(ImageResource* newImage)
 {
     setImageWithoutConsideringPendingLoadEvent(newImage);
 
@@ -111,10 +111,10 @@
     updatedHasPendingEvent();
 }
 
-void ImageLoader::setImageWithoutConsideringPendingLoadEvent(CachedImage* newImage)
+void ImageLoader::setImageWithoutConsideringPendingLoadEvent(ImageResource* newImage)
 {
     ASSERT(m_failedLoadURL.isEmpty());
-    CachedImage* oldImage = m_image.get();
+    ImageResource* oldImage = m_image.get();
     if (newImage != oldImage) {
         sourceImageChanged();
         m_image = newImage;
@@ -156,7 +156,7 @@
 
     // Do not load any image if the 'src' attribute is missing or if it is
     // an empty string.
-    ResourcePtr<CachedImage> newImage = 0;
+    ResourcePtr<ImageResource> newImage = 0;
     if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) {
         FetchRequest request(ResourceRequest(document->completeURL(sourceURI(attr))), element()->localName());
 
@@ -169,7 +169,7 @@
         if (m_loadManually) {
             bool autoLoadOtherImages = document->fetcher()->autoLoadImages();
             document->fetcher()->setAutoLoadImages(false);
-            newImage = new CachedImage(request.resourceRequest());
+            newImage = new ImageResource(request.resourceRequest());
             newImage->setLoading(true);
             document->fetcher()->m_documentResources.set(newImage->url(), newImage.get());
             document->fetcher()->setAutoLoadImages(autoLoadOtherImages);
@@ -193,7 +193,7 @@
         errorEventSender().dispatchEventSoon(this);
     }
 
-    CachedImage* oldImage = m_image.get();
+    ImageResource* oldImage = m_image.get();
     if (newImage != oldImage) {
         sourceImageChanged();
 
@@ -276,7 +276,7 @@
         m_hasPendingErrorEvent = true;
         errorEventSender().dispatchEventSoon(this);
 
-        DEFINE_STATIC_LOCAL(String, consoleMessage, (ASCIILiteral("Cross-origin image load denied by Cross-Origin Resource Sharing policy.")));
+        DEFINE_STATIC_LOCAL(String, consoleMessage, ("Cross-origin image load denied by Cross-Origin Resource Sharing policy."));
         m_element->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
 
         ASSERT(!m_hasPendingLoadEvent);
@@ -329,9 +329,9 @@
     // Only update the renderer if it doesn't have an image or if what we have
     // is a complete image.  This prevents flickering in the case where a dynamic
     // change is happening between two images.
-    CachedImage* cachedImage = imageResource->cachedImage();
+    ImageResource* cachedImage = imageResource->cachedImage();
     if (m_image != cachedImage && (m_imageComplete || !cachedImage))
-        imageResource->setCachedImage(m_image.get());
+        imageResource->setImageResource(m_image.get());
 }
 
 void ImageLoader::updatedHasPendingEvent()
diff --git a/Source/core/loader/ImageLoader.h b/Source/core/loader/ImageLoader.h
index 26b3d0b..dfb6ad0 100644
--- a/Source/core/loader/ImageLoader.h
+++ b/Source/core/loader/ImageLoader.h
@@ -23,8 +23,8 @@
 #ifndef ImageLoader_h
 #define ImageLoader_h
 
-#include "core/loader/cache/CachedImage.h"
-#include "core/loader/cache/CachedImageClient.h"
+#include "core/loader/cache/ImageResource.h"
+#include "core/loader/cache/ImageResourceClient.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "wtf/HashSet.h"
 #include "wtf/text/AtomicString.h"
@@ -35,7 +35,7 @@
 public:
     virtual void notifyImageSourceChanged() = 0;
 
-    // Determines whether the observed CachedImage should have higher priority in the decoded resources cache.
+    // Determines whether the observed ImageResource should have higher priority in the decoded resources cache.
     virtual bool requestsHighLiveResourceCachePriority() { return false; }
 
 protected:
@@ -49,7 +49,7 @@
 template<typename T> class EventSender;
 typedef EventSender<ImageLoader> ImageEventSender;
 
-class ImageLoader : public CachedImageClient {
+class ImageLoader : public ImageResourceClient {
 public:
     explicit ImageLoader(Element*);
     virtual ~ImageLoader();
@@ -67,8 +67,8 @@
     Element* element() const { return m_element; }
     bool imageComplete() const { return m_imageComplete; }
 
-    CachedImage* image() const { return m_image.get(); }
-    void setImage(CachedImage*); // Cancels pending beforeload and load events, and doesn't dispatch new ones.
+    ImageResource* image() const { return m_image.get(); }
+    void setImage(ImageResource*); // Cancels pending beforeload and load events, and doesn't dispatch new ones.
 
     void setLoadManually(bool loadManually) { m_loadManually = loadManually; }
 
@@ -100,14 +100,14 @@
     RenderImageResource* renderImageResource();
     void updateRenderer();
 
-    void setImageWithoutConsideringPendingLoadEvent(CachedImage*);
+    void setImageWithoutConsideringPendingLoadEvent(ImageResource*);
     void sourceImageChanged();
     void clearFailedLoadURL();
 
     void timerFired(Timer<ImageLoader>*);
 
     Element* m_element;
-    ResourcePtr<CachedImage> m_image;
+    ResourcePtr<ImageResource> m_image;
     HashSet<ImageLoaderClient*> m_clients;
     Timer<ImageLoader> m_derefElementTimer;
     AtomicString m_failedLoadURL;
diff --git a/Source/core/loader/NavigationAction.h b/Source/core/loader/NavigationAction.h
index 9406728..a402d95 100644
--- a/Source/core/loader/NavigationAction.h
+++ b/Source/core/loader/NavigationAction.h
@@ -47,11 +47,7 @@
         NavigationAction(const ResourceRequest&, NavigationType, PassRefPtr<Event>);
         NavigationAction(const ResourceRequest&, FrameLoadType, bool isFormSubmission, PassRefPtr<Event>);
 
-        bool isEmpty() const { return m_resourceRequest.url().isEmpty(); }
-
-        KURL url() const { return m_resourceRequest.url(); }
         const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
-
         NavigationType type() const { return m_type; }
         Event* event() const { return m_event.get(); }
 
diff --git a/Source/core/loader/NavigationScheduler.cpp b/Source/core/loader/NavigationScheduler.cpp
index 183f53a..9547744 100644
--- a/Source/core/loader/NavigationScheduler.cpp
+++ b/Source/core/loader/NavigationScheduler.cpp
@@ -313,7 +313,7 @@
 {
     // Non-user navigation before the page has finished firing onload should not create a new back/forward item.
     // See https://webkit.org/b/42861 for the original motivation for this.
-    if (!ScriptController::processingUserGesture() && targetFrame->loader()->documentLoader() && !targetFrame->loader()->documentLoader()->wasOnloadHandled())
+    if (!ScriptController::processingUserGesture() && !targetFrame->document()->loadEventFinished())
         return true;
 
     // Navigation of a subframe during loading of an ancestor frame does not create a new back/forward item.
diff --git a/Source/core/loader/ResourceLoader.cpp b/Source/core/loader/ResourceLoader.cpp
index 1e799cc..389cab4 100644
--- a/Source/core/loader/ResourceLoader.cpp
+++ b/Source/core/loader/ResourceLoader.cpp
@@ -34,6 +34,7 @@
 #include "core/loader/cache/Resource.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/Logging.h"
+#include "core/platform/SharedBuffer.h"
 #include "core/platform/chromium/support/WrappedResourceRequest.h"
 #include "core/platform/chromium/support/WrappedResourceResponse.h"
 #include "core/platform/network/ResourceError.h"
@@ -402,7 +403,9 @@
 
     error = errorOut;
     data.clear();
-    data.append(dataOut.data(), dataOut.size());
+    RefPtr<SharedBuffer> buffer = dataOut;
+    if (buffer)
+        buffer->moveTo(data);
 }
 
 }
diff --git a/Source/core/loader/SubstituteData.cpp b/Source/core/loader/SubstituteData.cpp
deleted file mode 100644
index 74f241e..0000000
--- a/Source/core/loader/SubstituteData.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/loader/SubstituteData.h"
-
-namespace WebCore {
-
-}
diff --git a/Source/core/loader/SubstituteData.h b/Source/core/loader/SubstituteData.h
index 704f314..ad6f2b7 100644
--- a/Source/core/loader/SubstituteData.h
+++ b/Source/core/loader/SubstituteData.h
@@ -37,12 +37,11 @@
     public:
         SubstituteData() { }
 
-        SubstituteData(PassRefPtr<SharedBuffer> content, const String& mimeType, const String& textEncoding, const KURL& failingURL, const KURL& responseURL = KURL())
+        SubstituteData(PassRefPtr<SharedBuffer> content, const String& mimeType, const String& textEncoding, const KURL& failingURL)
             : m_content(content)
             , m_mimeType(mimeType)
             , m_textEncoding(textEncoding)
             , m_failingURL(failingURL)
-            , m_responseURL(responseURL)
         {
         }
 
@@ -52,7 +51,6 @@
         const String& mimeType() const { return m_mimeType; }
         const String& textEncoding() const { return m_textEncoding; }
         const KURL& failingURL() const { return m_failingURL; }
-        const KURL& responseURL() const { return m_responseURL; }
 
     private:
         RefPtr<SharedBuffer> m_content;
diff --git a/Source/core/loader/TextTrackLoader.cpp b/Source/core/loader/TextTrackLoader.cpp
index 190edc6..9c548eb 100644
--- a/Source/core/loader/TextTrackLoader.cpp
+++ b/Source/core/loader/TextTrackLoader.cpp
@@ -31,9 +31,9 @@
 #include "core/dom/Document.h"
 #include "core/html/track/WebVTTParser.h"
 #include "core/loader/CrossOriginAccessControl.h"
-#include "core/loader/cache/CachedTextTrack.h"
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/ResourceFetcher.h"
+#include "core/loader/cache/TextTrackResource.h"
 #include "core/platform/Logging.h"
 #include "core/platform/SharedBuffer.h"
 #include "weborigin/SecurityOrigin.h"
@@ -113,7 +113,7 @@
 
 void TextTrackLoader::corsPolicyPreventedLoad()
 {
-    DEFINE_STATIC_LOCAL(String, consoleMessage, (ASCIILiteral("Cross-origin text track load denied by Cross-Origin Resource Sharing policy.")));
+    DEFINE_STATIC_LOCAL(String, consoleMessage, ("Cross-origin text track load denied by Cross-Origin Resource Sharing policy."));
     Document* document = toDocument(m_scriptExecutionContext);
     document->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
     m_state = Failed;
diff --git a/Source/core/loader/TextTrackLoader.h b/Source/core/loader/TextTrackLoader.h
index 8680ab6..dd2feeb 100644
--- a/Source/core/loader/TextTrackLoader.h
+++ b/Source/core/loader/TextTrackLoader.h
@@ -27,9 +27,9 @@
 #define TextTrackLoader_h
 
 #include "core/html/track/WebVTTParser.h"
-#include "core/loader/cache/CachedTextTrack.h"
 #include "core/loader/cache/ResourceClient.h"
 #include "core/loader/cache/ResourcePtr.h"
+#include "core/loader/cache/TextTrackResource.h"
 #include "core/platform/Timer.h"
 #include "wtf/OwnPtr.h"
 
@@ -93,7 +93,7 @@
 
     TextTrackLoaderClient* m_client;
     OwnPtr<WebVTTParser> m_cueParser;
-    ResourcePtr<CachedTextTrack> m_cachedCueData;
+    ResourcePtr<TextTrackResource> m_cachedCueData;
     ScriptExecutionContext* m_scriptExecutionContext;
     Timer<TextTrackLoader> m_cueLoadTimer;
     String m_crossOriginMode;
diff --git a/Source/core/loader/appcache/DOMApplicationCache.idl b/Source/core/loader/appcache/DOMApplicationCache.idl
index f1c98e6..8dc4c23 100644
--- a/Source/core/loader/appcache/DOMApplicationCache.idl
+++ b/Source/core/loader/appcache/DOMApplicationCache.idl
@@ -41,13 +41,13 @@
     void abort();
 
     // events
-    attribute EventListener onchecking;
-    attribute EventListener onerror;
-    attribute EventListener onnoupdate;
-    attribute EventListener ondownloading;
-    attribute EventListener onprogress;
-    attribute EventListener onupdateready;
-    attribute EventListener oncached;
-    attribute EventListener onobsolete;
+    attribute EventHandler onchecking;
+    attribute EventHandler onerror;
+    attribute EventHandler onnoupdate;
+    attribute EventHandler ondownloading;
+    attribute EventHandler onprogress;
+    attribute EventHandler onupdateready;
+    attribute EventHandler oncached;
+    attribute EventHandler onobsolete;
 };
 
diff --git a/Source/core/loader/cache/CachedCSSStyleSheet.cpp b/Source/core/loader/cache/CSSStyleSheetResource.cpp
similarity index 79%
rename from Source/core/loader/cache/CachedCSSStyleSheet.cpp
rename to Source/core/loader/cache/CSSStyleSheetResource.cpp
index c9ce9bd..53398a2 100644
--- a/Source/core/loader/cache/CachedCSSStyleSheet.cpp
+++ b/Source/core/loader/cache/CSSStyleSheetResource.cpp
@@ -25,12 +25,12 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
+#include "core/loader/cache/CSSStyleSheetResource.h"
 
 #include "core/css/StyleSheetContents.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/CachedStyleSheetClient.h"
 #include "core/loader/cache/ResourceClientWalker.h"
+#include "core/loader/cache/StyleSheetResourceClient.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/network/HTTPParsers.h"
 #include "wtf/CurrentTime.h"
@@ -38,7 +38,7 @@
 
 namespace WebCore {
 
-CachedCSSStyleSheet::CachedCSSStyleSheet(const ResourceRequest& resourceRequest, const String& charset)
+CSSStyleSheetResource::CSSStyleSheetResource(const ResourceRequest& resourceRequest, const String& charset)
     : Resource(resourceRequest, CSSStyleSheet)
     , m_decoder(TextResourceDecoder::create("text/css", charset))
 {
@@ -49,35 +49,35 @@
     setAccept(acceptCSS);
 }
 
-CachedCSSStyleSheet::~CachedCSSStyleSheet()
+CSSStyleSheetResource::~CSSStyleSheetResource()
 {
     if (m_parsedStyleSheetCache)
         m_parsedStyleSheetCache->removedFromMemoryCache();
 }
 
-void CachedCSSStyleSheet::didAddClient(ResourceClient* c)
+void CSSStyleSheetResource::didAddClient(ResourceClient* c)
 {
-    ASSERT(c->resourceClientType() == CachedStyleSheetClient::expectedType());
+    ASSERT(c->resourceClientType() == StyleSheetResourceClient::expectedType());
     // Resource::didAddClient() must be before setCSSStyleSheet(),
     // because setCSSStyleSheet() may cause scripts to be executed, which could destroy 'c' if it is an instance of HTMLLinkElement.
     // see the comment of HTMLLinkElement::setCSSStyleSheet.
     Resource::didAddClient(c);
 
     if (!isLoading())
-        static_cast<CachedStyleSheetClient*>(c)->setCSSStyleSheet(m_resourceRequest.url(), m_response.url(), m_decoder->encoding().name(), this);
+        static_cast<StyleSheetResourceClient*>(c)->setCSSStyleSheet(m_resourceRequest.url(), m_response.url(), m_decoder->encoding().name(), this);
 }
 
-void CachedCSSStyleSheet::setEncoding(const String& chs)
+void CSSStyleSheetResource::setEncoding(const String& chs)
 {
     m_decoder->setEncoding(chs, TextResourceDecoder::EncodingFromHTTPHeader);
 }
 
-String CachedCSSStyleSheet::encoding() const
+String CSSStyleSheetResource::encoding() const
 {
     return m_decoder->encoding().name();
 }
 
-const String CachedCSSStyleSheet::sheetText(bool enforceMIMEType, bool* hasValidMIMEType) const
+const String CSSStyleSheetResource::sheetText(bool enforceMIMEType, bool* hasValidMIMEType) const
 {
     ASSERT(!isPurgeable());
 
@@ -93,7 +93,7 @@
     return sheetText;
 }
 
-void CachedCSSStyleSheet::checkNotify()
+void CSSStyleSheetResource::checkNotify()
 {
     // Decode the data to find out the encoding and keep the sheet text around during checkNotify()
     if (m_data) {
@@ -101,14 +101,14 @@
         m_decodedSheetText.append(m_decoder->flush());
     }
 
-    ResourceClientWalker<CachedStyleSheetClient> w(m_clients);
-    while (CachedStyleSheetClient* c = w.next())
+    ResourceClientWalker<StyleSheetResourceClient> w(m_clients);
+    while (StyleSheetResourceClient* c = w.next())
         c->setCSSStyleSheet(m_resourceRequest.url(), m_response.url(), m_decoder->encoding().name(), this);
     // Clear the decoded text as it is unlikely to be needed immediately again and is cheap to regenerate.
     m_decodedSheetText = String();
 }
 
-bool CachedCSSStyleSheet::canUseSheet(bool enforceMIMEType, bool* hasValidMIMEType) const
+bool CSSStyleSheetResource::canUseSheet(bool enforceMIMEType, bool* hasValidMIMEType) const
 {
     if (errorOccurred())
         return false;
@@ -116,9 +116,9 @@
     if (!enforceMIMEType && !hasValidMIMEType)
         return true;
 
-    // This check exactly matches Firefox.  Note that we grab the Content-Type
+    // This check exactly matches Firefox. Note that we grab the Content-Type
     // header directly because we want to see what the value is BEFORE content
-    // sniffing.  Firefox does this by setting a "type hint" on the channel.
+    // sniffing. Firefox does this by setting a "type hint" on the channel.
     // This implementation should be observationally equivalent.
     //
     // This code defaults to allowing the stylesheet for non-HTTP protocols so
@@ -132,7 +132,7 @@
     return typeOK;
 }
 
-void CachedCSSStyleSheet::destroyDecodedData()
+void CSSStyleSheetResource::destroyDecodedData()
 {
     if (!m_parsedStyleSheetCache)
         return;
@@ -146,7 +146,7 @@
         makePurgeable(true);
 }
 
-PassRefPtr<StyleSheetContents> CachedCSSStyleSheet::restoreParsedStyleSheet(const CSSParserContext& context)
+PassRefPtr<StyleSheetContents> CSSStyleSheetResource::restoreParsedStyleSheet(const CSSParserContext& context)
 {
     if (!m_parsedStyleSheetCache)
         return 0;
@@ -168,7 +168,7 @@
     return m_parsedStyleSheetCache;
 }
 
-void CachedCSSStyleSheet::saveParsedStyleSheet(PassRefPtr<StyleSheetContents> sheet)
+void CSSStyleSheetResource::saveParsedStyleSheet(PassRefPtr<StyleSheetContents> sheet)
 {
     ASSERT(sheet && sheet->isCacheable());
 
diff --git a/Source/core/loader/cache/CSSStyleSheetResource.h b/Source/core/loader/cache/CSSStyleSheetResource.h
new file mode 100644
index 0000000..b01fa86
--- /dev/null
+++ b/Source/core/loader/cache/CSSStyleSheetResource.h
@@ -0,0 +1,67 @@
+/*
+    Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
+    Copyright (C) 2001 Dirk Mueller <mueller@kde.org>
+    Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+    Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+
+    You should have received a copy of the GNU Library General Public License
+    along with this library; see the file COPYING.LIB.  If not, write to
+    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+    Boston, MA 02110-1301, USA.
+
+    This class provides all functionality needed for loading images, style sheets and html
+    pages from the web. It has a memory cache for these objects.
+*/
+
+#ifndef CSSStyleSheetResource_h
+#define CSSStyleSheetResource_h
+
+#include "core/loader/cache/Resource.h"
+
+namespace WebCore {
+
+class ResourceClient;
+class StyleSheetContents;
+class TextResourceDecoder;
+struct CSSParserContext;
+
+class CSSStyleSheetResource : public Resource {
+public:
+    CSSStyleSheetResource(const ResourceRequest&, const String& charset);
+    virtual ~CSSStyleSheetResource();
+
+    const String sheetText(bool enforceMIMEType = true, bool* hasValidMIMEType = 0) const;
+
+    virtual void didAddClient(ResourceClient*);
+    virtual void setEncoding(const String&);
+    virtual String encoding() const;
+    virtual void destroyDecodedData() OVERRIDE;
+
+    PassRefPtr<StyleSheetContents> restoreParsedStyleSheet(const CSSParserContext&);
+    void saveParsedStyleSheet(PassRefPtr<StyleSheetContents>);
+
+private:
+    bool canUseSheet(bool enforceMIMEType, bool* hasValidMIMEType) const;
+
+protected:
+    virtual void checkNotify();
+
+    RefPtr<TextResourceDecoder> m_decoder;
+    String m_decodedSheetText;
+
+    RefPtr<StyleSheetContents> m_parsedStyleSheetCache;
+};
+
+}
+
+#endif
diff --git a/Source/core/loader/cache/CachedCSSStyleSheet.h b/Source/core/loader/cache/CachedCSSStyleSheet.h
deleted file mode 100644
index e368760..0000000
--- a/Source/core/loader/cache/CachedCSSStyleSheet.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
-    Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
-    Copyright (C) 2001 Dirk Mueller <mueller@kde.org>
-    Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
-    Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Library General Public
-    License as published by the Free Software Foundation; either
-    version 2 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Library General Public License for more details.
-
-    You should have received a copy of the GNU Library General Public License
-    along with this library; see the file COPYING.LIB.  If not, write to
-    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-    Boston, MA 02110-1301, USA.
-
-    This class provides all functionality needed for loading images, style sheets and html
-    pages from the web. It has a memory cache for these objects.
-*/
-
-#ifndef CachedCSSStyleSheet_h
-#define CachedCSSStyleSheet_h
-
-#include "core/loader/cache/Resource.h"
-
-namespace WebCore {
-
-class ResourceClient;
-    class StyleSheetContents;
-    class TextResourceDecoder;
-    struct CSSParserContext;
-
-    class CachedCSSStyleSheet : public Resource {
-    public:
-        CachedCSSStyleSheet(const ResourceRequest&, const String& charset);
-        virtual ~CachedCSSStyleSheet();
-
-        const String sheetText(bool enforceMIMEType = true, bool* hasValidMIMEType = 0) const;
-
-        virtual void didAddClient(ResourceClient*);
-        virtual void setEncoding(const String&);
-        virtual String encoding() const;
-        virtual void destroyDecodedData() OVERRIDE;
-
-        PassRefPtr<StyleSheetContents> restoreParsedStyleSheet(const CSSParserContext&);
-        void saveParsedStyleSheet(PassRefPtr<StyleSheetContents>);
-
-    private:
-        bool canUseSheet(bool enforceMIMEType, bool* hasValidMIMEType) const;
-
-    protected:
-        virtual void checkNotify();
-
-        RefPtr<TextResourceDecoder> m_decoder;
-        String m_decodedSheetText;
-
-        RefPtr<StyleSheetContents> m_parsedStyleSheetCache;
-    };
-
-}
-
-#endif
diff --git a/Source/core/loader/cache/CachedDocument.cpp b/Source/core/loader/cache/DocumentResource.cpp
similarity index 83%
rename from Source/core/loader/cache/CachedDocument.cpp
rename to Source/core/loader/cache/DocumentResource.cpp
index ad831ca..2750341 100644
--- a/Source/core/loader/cache/CachedDocument.cpp
+++ b/Source/core/loader/cache/DocumentResource.cpp
@@ -22,7 +22,7 @@
 
 #include "config.h"
 
-#include "core/loader/cache/CachedDocument.h"
+#include "core/loader/cache/DocumentResource.h"
 
 #include "core/loader/cache/ResourceClient.h"
 #include "core/loader/cache/ResourcePtr.h"
@@ -32,29 +32,29 @@
 
 namespace WebCore {
 
-CachedDocument::CachedDocument(const ResourceRequest& request, Type type)
+DocumentResource::DocumentResource(const ResourceRequest& request, Type type)
     : Resource(request, type)
     , m_decoder(TextResourceDecoder::create("application/xml"))
 {
     // FIXME: We'll support more types to support HTMLImports.
-    ASSERT(type == SVGDocumentResource);
+    ASSERT(type == SVGDocument);
 }
 
-CachedDocument::~CachedDocument()
+DocumentResource::~DocumentResource()
 {
 }
 
-void CachedDocument::setEncoding(const String& chs)
+void DocumentResource::setEncoding(const String& chs)
 {
     m_decoder->setEncoding(chs, TextResourceDecoder::EncodingFromHTTPHeader);
 }
 
-String CachedDocument::encoding() const
+String DocumentResource::encoding() const
 {
     return m_decoder->encoding().name();
 }
 
-void CachedDocument::checkNotify()
+void DocumentResource::checkNotify()
 {
     if (m_data) {
         StringBuilder decodedText;
@@ -67,10 +67,10 @@
     Resource::checkNotify();
 }
 
-PassRefPtr<Document> CachedDocument::createDocument(const KURL& url)
+PassRefPtr<Document> DocumentResource::createDocument(const KURL& url)
 {
     switch (type()) {
-    case SVGDocumentResource:
+    case SVGDocument:
         return SVGDocument::create(DocumentInit(url));
     default:
         // FIXME: We'll add more types to support HTMLImports.
diff --git a/Source/core/loader/cache/CachedDocument.h b/Source/core/loader/cache/DocumentResource.h
similarity index 84%
rename from Source/core/loader/cache/CachedDocument.h
rename to Source/core/loader/cache/DocumentResource.h
index 388caca..62379d7 100644
--- a/Source/core/loader/cache/CachedDocument.h
+++ b/Source/core/loader/cache/DocumentResource.h
@@ -20,8 +20,8 @@
     Boston, MA 02110-1301, USA.
 */
 
-#ifndef CachedDocument_h
-#define CachedDocument_h
+#ifndef DocumentResource_h
+#define DocumentResource_h
 
 #include "core/loader/TextResourceDecoder.h"
 #include "core/loader/cache/Resource.h"
@@ -32,10 +32,10 @@
 
 class Document;
 
-class CachedDocument : public Resource {
+class DocumentResource : public Resource {
 public:
-    CachedDocument(const ResourceRequest&, Type);
-    virtual ~CachedDocument();
+    DocumentResource(const ResourceRequest&, Type);
+    virtual ~DocumentResource();
 
     Document* document() const { return m_document.get(); }
 
@@ -50,13 +50,13 @@
     RefPtr<TextResourceDecoder> m_decoder;
 };
 
-class CachedDocumentClient : public ResourceClient {
+class DocumentResourceClient : public ResourceClient {
 public:
-    virtual ~CachedDocumentClient() { }
+    virtual ~DocumentResourceClient() { }
     static ResourceClientType expectedType() { return DocumentType; }
     virtual ResourceClientType resourceClientType() const { return expectedType(); }
 };
 
 }
 
-#endif // CachedDocument_h
+#endif // DocumentResource_h
diff --git a/Source/core/loader/cache/CachedSVGDocumentReference.h b/Source/core/loader/cache/DocumentResourceReference.h
similarity index 74%
rename from Source/core/loader/cache/CachedSVGDocumentReference.h
rename to Source/core/loader/cache/DocumentResourceReference.h
index 158b088..4d7009c 100644
--- a/Source/core/loader/cache/CachedSVGDocumentReference.h
+++ b/Source/core/loader/cache/DocumentResourceReference.h
@@ -23,21 +23,21 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CachedSVGDocumentReference_h
-#define CachedSVGDocumentReference_h
+#ifndef DocumentResourceReference_h
+#define DocumentResourceReference_h
 
-#include "core/loader/cache/CachedDocument.h"
+#include "core/loader/cache/DocumentResource.h"
 #include "core/loader/cache/ResourcePtr.h"
 
 namespace WebCore {
 
-class CachedSVGDocumentReference : public CachedDocumentClient {
+class DocumentResourceReference : public DocumentResourceClient {
 public:
-    CachedSVGDocumentReference(CachedDocument* document) : m_document(document) { m_document->addClient(this); }
-    virtual ~CachedSVGDocumentReference() { m_document->removeClient(this); }
-    CachedDocument* document() { return m_document.get(); }
+    DocumentResourceReference(DocumentResource* document) : m_document(document) { m_document->addClient(this); }
+    virtual ~DocumentResourceReference() { m_document->removeClient(this); }
+    DocumentResource* document() { return m_document.get(); }
 private:
-    ResourcePtr<CachedDocument> m_document;
+    ResourcePtr<DocumentResource> m_document;
 };
 
 };
diff --git a/Source/core/loader/cache/FetchRequest.h b/Source/core/loader/cache/FetchRequest.h
index fb878f7..974fff2 100644
--- a/Source/core/loader/cache/FetchRequest.h
+++ b/Source/core/loader/cache/FetchRequest.h
@@ -47,6 +47,7 @@
 
     ResourceRequest& mutableResourceRequest() { return m_resourceRequest; }
     const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
+    const KURL& url() const { return m_resourceRequest.url(); }
     const String& charset() const { return m_charset; }
     void setCharset(const String& charset) { m_charset = charset; }
     const ResourceLoaderOptions& options() const { return m_options; }
diff --git a/Source/core/loader/cache/CachedFont.cpp b/Source/core/loader/cache/FontResource.cpp
similarity index 76%
rename from Source/core/loader/cache/CachedFont.cpp
rename to Source/core/loader/cache/FontResource.cpp
index 69e06ac..90b5277 100644
--- a/Source/core/loader/cache/CachedFont.cpp
+++ b/Source/core/loader/cache/FontResource.cpp
@@ -25,7 +25,7 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/CachedFont.h"
+#include "core/loader/cache/FontResource.h"
 
 #include "core/loader/TextResourceDecoder.h"
 #include "core/loader/cache/ResourceClient.h"
@@ -43,43 +43,43 @@
 
 namespace WebCore {
 
-CachedFont::CachedFont(const ResourceRequest& resourceRequest)
-    : Resource(resourceRequest, FontResource)
+FontResource::FontResource(const ResourceRequest& resourceRequest)
+    : Resource(resourceRequest, Font)
     , m_loadInitiated(false)
 {
 }
 
-CachedFont::~CachedFont()
+FontResource::~FontResource()
 {
 }
 
-void CachedFont::load(ResourceFetcher*, const ResourceLoaderOptions& options)
+void FontResource::load(ResourceFetcher*, const ResourceLoaderOptions& options)
 {
-    // Don't load the file yet.  Wait for an access before triggering the load.
+    // Don't load the file yet. Wait for an access before triggering the load.
     setLoading(true);
     m_options = options;
 }
 
-void CachedFont::didAddClient(ResourceClient* c)
+void FontResource::didAddClient(ResourceClient* c)
 {
-    ASSERT(c->resourceClientType() == CachedFontClient::expectedType());
+    ASSERT(c->resourceClientType() == FontResourceClient::expectedType());
     if (!isLoading())
-        static_cast<CachedFontClient*>(c)->fontLoaded(this);
+        static_cast<FontResourceClient*>(c)->fontLoaded(this);
 }
 
-void CachedFont::beginLoadIfNeeded(ResourceFetcher* dl)
+void FontResource::beginLoadIfNeeded(ResourceFetcher* dl)
 {
     if (!m_loadInitiated) {
         m_loadInitiated = true;
         Resource::load(dl, m_options);
 
-        ResourceClientWalker<CachedFontClient> walker(m_clients);
-        while (CachedFontClient* client = walker.next())
+        ResourceClientWalker<FontResourceClient> walker(m_clients);
+        while (FontResourceClient* client = walker.next())
             client->didStartFontLoad(this);
     }
 }
 
-bool CachedFont::ensureCustomFontData()
+bool FontResource::ensureCustomFontData()
 {
     if (!m_fontData && !errorOccurred() && !isLoading() && m_data) {
         m_fontData = FontCustomPlatformData::create(m_data.get());
@@ -89,7 +89,7 @@
     return m_fontData;
 }
 
-FontPlatformData CachedFont::platformDataFromCustomData(float size, bool bold, bool italic, FontOrientation orientation, FontWidthVariant widthVariant)
+FontPlatformData FontResource::platformDataFromCustomData(float size, bool bold, bool italic, FontOrientation orientation, FontWidthVariant widthVariant)
 {
 #if ENABLE(SVG_FONTS)
     if (m_externalSVGDocument)
@@ -100,7 +100,7 @@
 }
 
 #if ENABLE(SVG_FONTS)
-bool CachedFont::ensureSVGFontData()
+bool FontResource::ensureSVGFontData()
 {
     if (!m_externalSVGDocument && !errorOccurred() && !isLoading() && m_data) {
         m_externalSVGDocument = SVGDocument::create();
@@ -118,7 +118,7 @@
     return m_externalSVGDocument;
 }
 
-SVGFontElement* CachedFont::getSVGFontById(const String& fontName) const
+SVGFontElement* FontResource::getSVGFontById(const String& fontName) const
 {
     RefPtr<NodeList> list = m_externalSVGDocument->getElementsByTagNameNS(SVGNames::fontTag.namespaceURI(), SVGNames::fontTag.localName());
     if (!list)
@@ -148,17 +148,17 @@
 }
 #endif
 
-void CachedFont::allClientsRemoved()
+void FontResource::allClientsRemoved()
 {
     m_fontData.clear();
     Resource::allClientsRemoved();
 }
 
-void CachedFont::checkNotify()
+void FontResource::checkNotify()
 {
-    ResourceClientWalker<CachedFontClient> w(m_clients);
-    while (CachedFontClient* c = w.next())
-         c->fontLoaded(this);
+    ResourceClientWalker<FontResourceClient> w(m_clients);
+    while (FontResourceClient* c = w.next())
+        c->fontLoaded(this);
 }
 
 }
diff --git a/Source/core/loader/cache/CachedFont.h b/Source/core/loader/cache/FontResource.h
similarity index 86%
rename from Source/core/loader/cache/CachedFont.h
rename to Source/core/loader/cache/FontResource.h
index 9faddca..5997f1e 100644
--- a/Source/core/loader/cache/CachedFont.h
+++ b/Source/core/loader/cache/FontResource.h
@@ -23,8 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CachedFont_h
-#define CachedFont_h
+#ifndef FontResource_h
+#define FontResource_h
 
 #include "core/loader/cache/Resource.h"
 #include "core/loader/cache/ResourceClient.h"
@@ -40,10 +40,10 @@
 class SVGFontElement;
 class FontCustomPlatformData;
 
-class CachedFont : public Resource {
+class FontResource : public Resource {
 public:
-    CachedFont(const ResourceRequest&);
-    virtual ~CachedFont();
+    FontResource(const ResourceRequest&);
+    virtual ~FontResource();
 
     virtual void load(ResourceFetcher*, const ResourceLoaderOptions&);
 
@@ -67,19 +67,19 @@
     bool m_loadInitiated;
 
 #if ENABLE(SVG_FONTS)
-    RefPtr<SVGDocument> m_externalSVGDocument;
+    RefPtr<WebCore::SVGDocument> m_externalSVGDocument;
 #endif
 
     friend class MemoryCache;
 };
 
-class CachedFontClient : public ResourceClient {
+class FontResourceClient : public ResourceClient {
 public:
-    virtual ~CachedFontClient() { }
+    virtual ~FontResourceClient() { }
     static ResourceClientType expectedType() { return FontType; }
     virtual ResourceClientType resourceClientType() const { return expectedType(); }
-    virtual void fontLoaded(CachedFont*) { }
-    virtual void didStartFontLoad(CachedFont*) { }
+    virtual void fontLoaded(FontResource*) { }
+    virtual void didStartFontLoad(FontResource*) { }
 };
 
 }
diff --git a/Source/core/loader/cache/CachedImage.cpp b/Source/core/loader/cache/ImageResource.cpp
similarity index 72%
rename from Source/core/loader/cache/CachedImage.cpp
rename to Source/core/loader/cache/ImageResource.cpp
index 7bdf262..c07d864 100644
--- a/Source/core/loader/cache/CachedImage.cpp
+++ b/Source/core/loader/cache/ImageResource.cpp
@@ -22,9 +22,9 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 
-#include "core/loader/cache/CachedImageClient.h"
+#include "core/loader/cache/ImageResourceClient.h"
 #include "core/loader/cache/MemoryCache.h"
 #include "core/loader/cache/ResourceClient.h"
 #include "core/loader/cache/ResourceClientWalker.h"
@@ -38,12 +38,12 @@
 #include "wtf/StdLibExtras.h"
 #include "wtf/Vector.h"
 
-using std::max;
+using namespace std;
 
 namespace WebCore {
 
-CachedImage::CachedImage(const ResourceRequest& resourceRequest)
-    : Resource(resourceRequest, ImageResource)
+ImageResource::ImageResource(const ResourceRequest& resourceRequest)
+    : Resource(resourceRequest, Image)
     , m_image(0)
     , m_loadingMultipartContent(false)
 {
@@ -51,8 +51,8 @@
     setCustomAcceptHeader();
 }
 
-CachedImage::CachedImage(Image* image)
-    : Resource(ResourceRequest(), ImageResource)
+ImageResource::ImageResource(WebCore::Image* image)
+    : Resource(ResourceRequest(), Image)
     , m_image(image)
 {
     setStatus(Cached);
@@ -60,12 +60,12 @@
     setCustomAcceptHeader();
 }
 
-CachedImage::~CachedImage()
+ImageResource::~ImageResource()
 {
     clearImage();
 }
 
-void CachedImage::load(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
+void ImageResource::load(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
 {
     if (!fetcher || fetcher->autoLoadImages())
         Resource::load(fetcher, options);
@@ -73,33 +73,33 @@
         setLoading(false);
 }
 
-void CachedImage::didAddClient(ResourceClient* c)
+void ImageResource::didAddClient(ResourceClient* c)
 {
     if (m_data && !m_image && !errorOccurred()) {
         createImage();
         m_image->setData(m_data, true);
     }
 
-    ASSERT(c->resourceClientType() == CachedImageClient::expectedType());
+    ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
     if (m_image && !m_image->isNull())
-        static_cast<CachedImageClient*>(c)->imageChanged(this);
+        static_cast<ImageResourceClient*>(c)->imageChanged(this);
 
     Resource::didAddClient(c);
 }
 
-void CachedImage::didRemoveClient(ResourceClient* c)
+void ImageResource::didRemoveClient(ResourceClient* c)
 {
     ASSERT(c);
-    ASSERT(c->resourceClientType() == CachedImageClient::expectedType());
+    ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
 
-    m_pendingContainerSizeRequests.remove(static_cast<CachedImageClient*>(c));
+    m_pendingContainerSizeRequests.remove(static_cast<ImageResourceClient*>(c));
     if (m_svgImageCache)
-        m_svgImageCache->removeClientFromCache(static_cast<CachedImageClient*>(c));
+        m_svgImageCache->removeClientFromCache(static_cast<ImageResourceClient*>(c));
 
     Resource::didRemoveClient(c);
 }
 
-void CachedImage::switchClientsToRevalidatedResource()
+void ImageResource::switchClientsToRevalidatedResource()
 {
     ASSERT(resourceToRevalidate());
     ASSERT(resourceToRevalidate()->isImage());
@@ -110,16 +110,16 @@
         for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
             switchContainerSizeRequests.set(it->key, it->value);
         Resource::switchClientsToRevalidatedResource();
-        CachedImage* revalidatedCachedImage = static_cast<CachedImage*>(resourceToRevalidate());
+        ImageResource* revalidatedImageResource = static_cast<ImageResource*>(resourceToRevalidate());
         for (ContainerSizeRequests::iterator it = switchContainerSizeRequests.begin(); it != switchContainerSizeRequests.end(); ++it)
-            revalidatedCachedImage->setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
+            revalidatedImageResource->setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
         return;
     }
 
     Resource::switchClientsToRevalidatedResource();
 }
 
-void CachedImage::allClientsRemoved()
+void ImageResource::allClientsRemoved()
 {
     m_pendingContainerSizeRequests.clear();
     if (m_image && !errorOccurred())
@@ -127,29 +127,29 @@
     Resource::allClientsRemoved();
 }
 
-pair<Image*, float> CachedImage::brokenImage(float deviceScaleFactor) const
+pair<WebCore::Image*, float> ImageResource::brokenImage(float deviceScaleFactor) const
 {
     if (deviceScaleFactor >= 2) {
-        DEFINE_STATIC_LOCAL(Image*, brokenImageHiRes, (Image::loadPlatformResource("missingImage@2x").leakRef()));
+        DEFINE_STATIC_LOCAL(WebCore::Image*, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x").leakRef()));
         return std::make_pair(brokenImageHiRes, 2);
     }
 
-    DEFINE_STATIC_LOCAL(Image*, brokenImageLoRes, (Image::loadPlatformResource("missingImage").leakRef()));
+    DEFINE_STATIC_LOCAL(WebCore::Image*, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage").leakRef()));
     return std::make_pair(brokenImageLoRes, 1);
 }
 
-bool CachedImage::willPaintBrokenImage() const
+bool ImageResource::willPaintBrokenImage() const
 {
     return errorOccurred();
 }
 
-Image* CachedImage::image()
+WebCore::Image* ImageResource::image()
 {
     ASSERT(!isPurgeable());
 
     if (errorOccurred()) {
         // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
-        // deviceScaleFactor from here. It is critical that callers use CachedImage::brokenImage()
+        // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
         // when they need the real, deviceScaleFactor-appropriate broken image icon.
         return brokenImage(1).first;
     }
@@ -157,33 +157,33 @@
     if (m_image)
         return m_image.get();
 
-    return Image::nullImage();
+    return WebCore::Image::nullImage();
 }
 
-Image* CachedImage::imageForRenderer(const RenderObject* renderer)
+WebCore::Image* ImageResource::imageForRenderer(const RenderObject* renderer)
 {
     ASSERT(!isPurgeable());
 
     if (errorOccurred()) {
         // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
-        // deviceScaleFactor from here. It is critical that callers use CachedImage::brokenImage()
+        // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
         // when they need the real, deviceScaleFactor-appropriate broken image icon.
         return brokenImage(1).first;
     }
 
     if (!m_image)
-        return Image::nullImage();
+        return WebCore::Image::nullImage();
 
     if (m_image->isSVGImage()) {
-        Image* image = m_svgImageCache->imageForRenderer(renderer);
-        if (image != Image::nullImage())
+        WebCore::Image* image = m_svgImageCache->imageForRenderer(renderer);
+        if (image != WebCore::Image::nullImage())
             return image;
     }
 
     return m_image.get();
 }
 
-void CachedImage::setContainerSizeForRenderer(const CachedImageClient* renderer, const IntSize& containerSize, float containerZoom)
+void ImageResource::setContainerSizeForRenderer(const ImageResourceClient* renderer, const IntSize& containerSize, float containerZoom)
 {
     if (containerSize.isEmpty())
         return;
@@ -201,7 +201,7 @@
     m_svgImageCache->setContainerSizeForRenderer(renderer, containerSize, containerZoom);
 }
 
-bool CachedImage::usesImageContainerSize() const
+bool ImageResource::usesImageContainerSize() const
 {
     if (m_image)
         return m_image->usesContainerSize();
@@ -209,7 +209,7 @@
     return false;
 }
 
-bool CachedImage::imageHasRelativeWidth() const
+bool ImageResource::imageHasRelativeWidth() const
 {
     if (m_image)
         return m_image->hasRelativeWidth();
@@ -217,7 +217,7 @@
     return false;
 }
 
-bool CachedImage::imageHasRelativeHeight() const
+bool ImageResource::imageHasRelativeHeight() const
 {
     if (m_image)
         return m_image->hasRelativeHeight();
@@ -225,7 +225,7 @@
     return false;
 }
 
-LayoutSize CachedImage::imageSizeForRenderer(const RenderObject* renderer, float multiplier)
+LayoutSize ImageResource::imageSizeForRenderer(const RenderObject* renderer, float multiplier)
 {
     ASSERT(!isPurgeable());
 
@@ -254,20 +254,20 @@
     return imageSize;
 }
 
-void CachedImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
+void ImageResource::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
 {
     if (m_image)
         m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
 }
 
-void CachedImage::notifyObservers(const IntRect* changeRect)
+void ImageResource::notifyObservers(const IntRect* changeRect)
 {
-    ResourceClientWalker<CachedImageClient> w(m_clients);
-    while (CachedImageClient* c = w.next())
+    ResourceClientWalker<ImageResourceClient> w(m_clients);
+    while (ImageResourceClient* c = w.next())
         c->imageChanged(this, changeRect);
 }
 
-void CachedImage::clear()
+void ImageResource::clear()
 {
     destroyDecodedData();
     clearImage();
@@ -275,13 +275,13 @@
     setEncodedSize(0);
 }
 
-void CachedImage::setCustomAcceptHeader()
+void ImageResource::setCustomAcceptHeader()
 {
     DEFINE_STATIC_LOCAL(const AtomicString, acceptWebP, ("image/webp,*/*;q=0.8", AtomicString::ConstructFromLiteral));
     setAccept(acceptWebP);
 }
 
-inline void CachedImage::createImage()
+inline void ImageResource::createImage()
 {
     // Create the image if it doesn't yet exist.
     if (m_image)
@@ -291,8 +291,9 @@
         RefPtr<SVGImage> svgImage = SVGImage::create(this);
         m_svgImageCache = SVGImageCache::create(svgImage.get());
         m_image = svgImage.release();
-    } else
+    } else {
         m_image = BitmapImage::create(this);
+    }
 
     if (m_image) {
         // Send queued container size requests.
@@ -304,7 +305,7 @@
     }
 }
 
-inline void CachedImage::clearImage()
+inline void ImageResource::clearImage()
 {
     // If our Image has an observer, it's always us so we need to clear the back pointer
     // before dropping our reference.
@@ -313,14 +314,14 @@
     m_image.clear();
 }
 
-void CachedImage::appendData(const char* data, int length)
+void ImageResource::appendData(const char* data, int length)
 {
     Resource::appendData(data, length);
     if (!m_loadingMultipartContent)
         updateImage(false);
 }
 
-void CachedImage::updateImage(bool allDataReceived)
+void ImageResource::updateImage(bool allDataReceived)
 {
     if (m_data)
         createImage();
@@ -334,7 +335,7 @@
         sizeAvailable = m_image->setData(m_data, allDataReceived);
 
     // Go ahead and tell our observers to try to draw if we have either
-    // received all the data or the size is known.  Each chunk from the
+    // received all the data or the size is known. Each chunk from the
     // network causes observers to repaint, which will force that chunk
     // to decode.
     if (sizeAvailable || allDataReceived) {
@@ -351,7 +352,7 @@
     }
 }
 
-void CachedImage::finishOnePart()
+void ImageResource::finishOnePart()
 {
     if (m_loadingMultipartContent)
         clear();
@@ -361,14 +362,14 @@
     Resource::finishOnePart();
 }
 
-void CachedImage::error(Resource::Status status)
+void ImageResource::error(Resource::Status status)
 {
     clear();
     Resource::error(status);
     notifyObservers();
 }
 
-void CachedImage::responseReceived(const ResourceResponse& response)
+void ImageResource::responseReceived(const ResourceResponse& response)
 {
     if (m_loadingMultipartContent && m_data)
         finishOnePart();
@@ -377,7 +378,7 @@
     Resource::responseReceived(response);
 }
 
-void CachedImage::destroyDecodedData()
+void ImageResource::destroyDecodedData()
 {
     bool canDeleteImage = !m_image || (m_image->hasOneRef() && m_image->isBitmapImage());
     if (isSafeToMakePurgeable() && canDeleteImage && !isLoading()) {
@@ -386,11 +387,12 @@
         m_image = 0;
         setDecodedSize(0);
         makePurgeable(true);
-    } else if (m_image && !errorOccurred())
+    } else if (m_image && !errorOccurred()) {
         m_image->destroyDecodedData();
+    }
 }
 
-void CachedImage::decodedSizeChanged(const Image* image, int delta)
+void ImageResource::decodedSizeChanged(const WebCore::Image* image, int delta)
 {
     if (!image || image != m_image)
         return;
@@ -398,7 +400,7 @@
     setDecodedSize(decodedSize() + delta);
 }
 
-void CachedImage::didDraw(const Image* image)
+void ImageResource::didDraw(const WebCore::Image* image)
 {
     if (!image || image != m_image)
         return;
@@ -410,13 +412,13 @@
     Resource::didAccessDecodedData(timeStamp);
 }
 
-bool CachedImage::shouldPauseAnimation(const Image* image)
+bool ImageResource::shouldPauseAnimation(const WebCore::Image* image)
 {
     if (!image || image != m_image)
         return false;
 
-    ResourceClientWalker<CachedImageClient> w(m_clients);
-    while (CachedImageClient* c = w.next()) {
+    ResourceClientWalker<ImageResourceClient> w(m_clients);
+    while (ImageResourceClient* c = w.next()) {
         if (c->willRenderImage(this))
             return false;
     }
@@ -424,23 +426,23 @@
     return true;
 }
 
-void CachedImage::animationAdvanced(const Image* image)
+void ImageResource::animationAdvanced(const WebCore::Image* image)
 {
     if (!image || image != m_image)
         return;
     notifyObservers();
 }
 
-void CachedImage::changedInRect(const Image* image, const IntRect& rect)
+void ImageResource::changedInRect(const WebCore::Image* image, const IntRect& rect)
 {
     if (!image || image != m_image)
         return;
     notifyObservers(&rect);
 }
 
-bool CachedImage::currentFrameKnownToBeOpaque(const RenderObject* renderer)
+bool ImageResource::currentFrameKnownToBeOpaque(const RenderObject* renderer)
 {
-    Image* image = imageForRenderer(renderer);
+    WebCore::Image* image = imageForRenderer(renderer);
     if (image->isBitmapImage())
         image->nativeImageForCurrentFrame(); // force decode
     return image->currentFrameKnownToBeOpaque();
diff --git a/Source/core/loader/cache/CachedImage.h b/Source/core/loader/cache/ImageResource.h
similarity index 76%
rename from Source/core/loader/cache/CachedImage.h
rename to Source/core/loader/cache/ImageResource.h
index 35abbf6..5bee694 100644
--- a/Source/core/loader/cache/CachedImage.h
+++ b/Source/core/loader/cache/ImageResource.h
@@ -20,8 +20,8 @@
     Boston, MA 02110-1301, USA.
 */
 
-#ifndef CachedImage_h
-#define CachedImage_h
+#ifndef ImageResource_h
+#define ImageResource_h
 
 #include "core/loader/cache/Resource.h"
 #include "core/platform/graphics/ImageObserver.h"
@@ -33,34 +33,34 @@
 
 namespace WebCore {
 
-class CachedImageClient;
+class ImageResourceClient;
 class ResourceFetcher;
 class FloatSize;
 class MemoryCache;
 class RenderObject;
 struct Length;
 
-class CachedImage : public Resource, public ImageObserver {
+class ImageResource : public Resource, public ImageObserver {
     friend class MemoryCache;
 
 public:
-    CachedImage(const ResourceRequest&);
-    CachedImage(Image*);
-    virtual ~CachedImage();
+    ImageResource(const ResourceRequest&);
+    ImageResource(WebCore::Image*);
+    virtual ~ImageResource();
 
     virtual void load(ResourceFetcher*, const ResourceLoaderOptions&);
 
-    Image* image(); // Returns the nullImage() if the image is not available yet.
-    Image* imageForRenderer(const RenderObject*); // Returns the nullImage() if the image is not available yet.
+    WebCore::Image* image(); // Returns the nullImage() if the image is not available yet.
+    WebCore::Image* imageForRenderer(const RenderObject*); // Returns the nullImage() if the image is not available yet.
     bool hasImage() const { return m_image.get(); }
     bool currentFrameKnownToBeOpaque(const RenderObject*); // Side effect: ensures decoded image is in cache, therefore should only be called when about to draw the image.
 
-    std::pair<Image*, float> brokenImage(float deviceScaleFactor) const; // Returns an image and the image's resolution scale factor.
+    std::pair<WebCore::Image*, float> brokenImage(float deviceScaleFactor) const; // Returns an image and the image's resolution scale factor.
     bool willPaintBrokenImage() const;
 
     bool canRender(const RenderObject* renderer, float multiplier) { return !errorOccurred() && !imageSizeForRenderer(renderer, multiplier).isEmpty(); }
 
-    void setContainerSizeForRenderer(const CachedImageClient*, const IntSize&, float);
+    void setContainerSizeForRenderer(const ImageResourceClient*, const IntSize&, float);
     bool usesImageContainerSize() const;
     bool imageHasRelativeWidth() const;
     bool imageHasRelativeHeight() const;
@@ -87,12 +87,12 @@
     virtual bool stillNeedsLoad() const OVERRIDE { return !errorOccurred() && status() == Unknown && !isLoading(); }
 
     // ImageObserver
-    virtual void decodedSizeChanged(const Image* image, int delta);
-    virtual void didDraw(const Image*);
+    virtual void decodedSizeChanged(const WebCore::Image*, int delta);
+    virtual void didDraw(const WebCore::Image*);
 
-    virtual bool shouldPauseAnimation(const Image*);
-    virtual void animationAdvanced(const Image*);
-    virtual void changedInRect(const Image*, const IntRect&);
+    virtual bool shouldPauseAnimation(const WebCore::Image*);
+    virtual void animationAdvanced(const WebCore::Image*);
+    virtual void changedInRect(const WebCore::Image*, const IntRect&);
 
 private:
     void clear();
@@ -107,10 +107,10 @@
     virtual void switchClientsToRevalidatedResource() OVERRIDE;
 
     typedef pair<IntSize, float> SizeAndZoom;
-    typedef HashMap<const CachedImageClient*, SizeAndZoom> ContainerSizeRequests;
+    typedef HashMap<const ImageResourceClient*, SizeAndZoom> ContainerSizeRequests;
     ContainerSizeRequests m_pendingContainerSizeRequests;
 
-    RefPtr<Image> m_image;
+    RefPtr<WebCore::Image> m_image;
     OwnPtr<SVGImageCache> m_svgImageCache;
     bool m_loadingMultipartContent;
 };
diff --git a/Source/core/loader/cache/CachedImageClient.h b/Source/core/loader/cache/ImageResourceClient.h
similarity index 85%
rename from Source/core/loader/cache/CachedImageClient.h
rename to Source/core/loader/cache/ImageResourceClient.h
index 6ac4829..4cea375 100644
--- a/Source/core/loader/cache/CachedImageClient.h
+++ b/Source/core/loader/cache/ImageResourceClient.h
@@ -20,31 +20,31 @@
     Boston, MA 02110-1301, USA.
 */
 
-#ifndef CachedImageClient_h
-#define CachedImageClient_h
+#ifndef ImageResourceClient_h
+#define ImageResourceClient_h
 
 #include "core/loader/cache/ResourceClient.h"
 
 namespace WebCore {
 
-class CachedImage;
+class ImageResource;
 class IntRect;
 
-class CachedImageClient : public ResourceClient {
+class ImageResourceClient : public ResourceClient {
 public:
-    virtual ~CachedImageClient() { }
+    virtual ~ImageResourceClient() { }
     static ResourceClientType expectedType() { return ImageType; }
     virtual ResourceClientType resourceClientType() const { return expectedType(); }
 
     // Called whenever a frame of an image changes, either because we got more data from the network or
     // because we are animating. If not null, the IntRect is the changed rect of the image.
-    virtual void imageChanged(CachedImage*, const IntRect* = 0) { }
+    virtual void imageChanged(ImageResource*, const IntRect* = 0) { }
 
     // Called to find out if this client wants to actually display the image. Used to tell when we
     // can halt animation. Content nodes that hold image refs for example would not render the image,
     // but RenderImages would (assuming they have visibility: visible and their render tree isn't hidden
     // e.g., in the b/f cache or in a background tab).
-    virtual bool willRenderImage(CachedImage*) { return false; }
+    virtual bool willRenderImage(ImageResource*) { return false; }
 };
 
 }
diff --git a/Source/core/loader/cache/CachedImageTest.cpp b/Source/core/loader/cache/ImageResourceTest.cpp
similarity index 92%
rename from Source/core/loader/cache/CachedImageTest.cpp
rename to Source/core/loader/cache/ImageResourceTest.cpp
index a39768b..37d558b 100644
--- a/Source/core/loader/cache/CachedImageTest.cpp
+++ b/Source/core/loader/cache/ImageResourceTest.cpp
@@ -29,13 +29,13 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/EmptyClients.h"
-#include "core/loader/cache/CachedImageClient.h"
+#include "core/loader/cache/ImageResourceClient.h"
 #include "core/loader/cache/MemoryCache.h"
-#include "core/loader/cache/MockCachedImageClient.h"
+#include "core/loader/cache/MockImageResourceClient.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/page/Frame.h"
@@ -66,12 +66,12 @@
     WebKit::Platform::current()->currentThread()->enterRunLoop();
 }
 
-TEST(CachedImageTest, MultipartImage)
+TEST(ImageResourceTest, MultipartImage)
 {
-    ResourcePtr<CachedImage> cachedImage = new CachedImage(ResourceRequest());
+    ResourcePtr<ImageResource> cachedImage = new ImageResource(ResourceRequest());
     cachedImage->setLoading(true);
 
-    MockCachedImageClient client;
+    MockImageResourceClient client;
     cachedImage->addClient(&client);
 
     // Send the multipart response. No image or data buffer is created.
@@ -110,7 +110,7 @@
     ASSERT_TRUE(client.notifyFinishedCalled());
 }
 
-TEST(CachedImageTest, CancelOnDetach)
+TEST(ImageResourceTest, CancelOnDetach)
 {
     KURL testURL(ParsedURLString, "http://www.test.com/cancelTest.html");
 
@@ -133,11 +133,11 @@
     documentLoader->setFrame(frame.get());
 
     // Emulate starting a real load.
-    ResourcePtr<CachedImage> cachedImage = new CachedImage(ResourceRequest(testURL));
+    ResourcePtr<ImageResource> cachedImage = new ImageResource(ResourceRequest(testURL));
     cachedImage->load(documentLoader->fetcher(), ResourceLoaderOptions());
     memoryCache()->add(cachedImage.get());
 
-    MockCachedImageClient client;
+    MockImageResourceClient client;
     cachedImage->addClient(&client);
     EXPECT_EQ(Resource::Pending, cachedImage->status());
 
diff --git a/Source/core/loader/cache/MemoryCache.cpp b/Source/core/loader/cache/MemoryCache.cpp
index cf4754a..c51f544 100644
--- a/Source/core/loader/cache/MemoryCache.cpp
+++ b/Source/core/loader/cache/MemoryCache.cpp
@@ -30,6 +30,7 @@
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/page/FrameView.h"
 #include "core/platform/Logging.h"
+#include "core/platform/chromium/TraceEvent.h"
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerLoaderProxy.h"
 #include "core/workers/WorkerThread.h"
@@ -151,7 +152,7 @@
 void MemoryCache::pruneLiveResources()
 {
     unsigned capacity = liveCapacity();
-    if (capacity && m_liveSize <= capacity)
+    if (!m_liveSize || (capacity && m_liveSize <= capacity))
         return;
 
     unsigned targetSize = static_cast<unsigned>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
@@ -198,7 +199,7 @@
 void MemoryCache::pruneDeadResources()
 {
     unsigned capacity = deadCapacity();
-    if (capacity && m_deadSize <= capacity)
+    if (!m_deadSize || (capacity && m_deadSize <= capacity))
         return;
 
     unsigned targetSize = static_cast<unsigned>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
@@ -524,7 +525,7 @@
     for (ResourceMap::iterator i = m_resources.begin(); i != e; ++i) {
         Resource* resource = i->value;
         switch (resource->type()) {
-        case Resource::ImageResource:
+        case Resource::Image:
             stats.images.addResource(resource);
             break;
         case Resource::CSSStyleSheet:
@@ -536,7 +537,7 @@
         case Resource::XSLStyleSheet:
             stats.xslStyleSheets.addResource(resource);
             break;
-        case Resource::FontResource:
+        case Resource::Font:
             stats.fonts.addResource(resource);
             break;
         default:
@@ -559,6 +560,7 @@
 
 void MemoryCache::prune()
 {
+    TRACE_EVENT0("renderer", "MemoryCache::prune()");
     if (m_liveSize + m_deadSize <= m_capacity && m_maxDeadCapacity && m_deadSize <= m_maxDeadCapacity) // Fast path.
         return;
     if (m_inPruneResources)
diff --git a/Source/core/loader/cache/MemoryCache.h b/Source/core/loader/cache/MemoryCache.h
index eed24f6..f174a11 100644
--- a/Source/core/loader/cache/MemoryCache.h
+++ b/Source/core/loader/cache/MemoryCache.h
@@ -34,7 +34,7 @@
 
 namespace WebCore  {
 
-class CachedCSSStyleSheet;
+class CSSStyleSheetResource;
 class Resource;
 class ResourceFetcher;
 class KURL;
diff --git a/Source/core/loader/cache/MemoryCacheTest.cpp b/Source/core/loader/cache/MemoryCacheTest.cpp
index b050359..1a36517 100644
--- a/Source/core/loader/cache/MemoryCacheTest.cpp
+++ b/Source/core/loader/cache/MemoryCacheTest.cpp
@@ -31,8 +31,8 @@
 #include "config.h"
 #include "core/loader/cache/MemoryCache.h"
 
-#include "core/loader/cache/CachedRawResource.h"
-#include "core/loader/cache/MockCachedImageClient.h"
+#include "core/loader/cache/MockImageResourceClient.h"
+#include "core/loader/cache/RawResource.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "wtf/OwnPtr.h"
@@ -43,9 +43,9 @@
 
 class MemoryCacheTest : public ::testing::Test {
 public:
-    class MockCachedImage : public WebCore::Resource {
+    class MockImageResource : public WebCore::Resource {
     public:
-        MockCachedImage(const ResourceRequest& request, Type type)
+        MockImageResource(const ResourceRequest& request, Type type)
             : Resource(request, type)
         {
         }
@@ -108,7 +108,7 @@
     memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
 
     ResourcePtr<Resource> cachedResource =
-        new Resource(ResourceRequest(""), Resource::RawResource);
+        new Resource(ResourceRequest(""), Resource::Raw);
     const char data[5] = "abcd";
     cachedResource->appendData(data, 3);
     // The resource size has to be nonzero for this test to be meaningful, but
@@ -132,13 +132,13 @@
 TEST_F(MemoryCacheTest, DecodeCacheOrder)
 {
     memoryCache()->setDelayBeforeLiveDecodedPrune(0);
-    ResourcePtr<MockCachedImage> cachedImageLowPriority =
-        new MockCachedImage(ResourceRequest(""), Resource::RawResource);
-    ResourcePtr<MockCachedImage> cachedImageHighPriority =
-        new MockCachedImage(ResourceRequest(""), Resource::RawResource);
+    ResourcePtr<MockImageResource> cachedImageLowPriority =
+        new MockImageResource(ResourceRequest(""), Resource::Raw);
+    ResourcePtr<MockImageResource> cachedImageHighPriority =
+        new MockImageResource(ResourceRequest(""), Resource::Raw);
 
-    MockCachedImageClient clientLowPriority;
-    MockCachedImageClient clientHighPriority;
+    MockImageResourceClient clientLowPriority;
+    MockImageResourceClient clientHighPriority;
     cachedImageLowPriority->addClient(&clientLowPriority);
     cachedImageHighPriority->addClient(&clientHighPriority);
 
diff --git a/Source/core/loader/cache/MockCachedImageClient.h b/Source/core/loader/cache/MockImageResourceClient.h
similarity index 85%
rename from Source/core/loader/cache/MockCachedImageClient.h
rename to Source/core/loader/cache/MockImageResourceClient.h
index e9729d5..adaa90f 100644
--- a/Source/core/loader/cache/MockCachedImageClient.h
+++ b/Source/core/loader/cache/MockImageResourceClient.h
@@ -28,10 +28,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef MockCachedImageClient_h
-#define MockCachedImageClient_h
+#ifndef MockImageResourceClient_h
+#define MockImageResourceClient_h
 
-#include "core/loader/cache/CachedImageClient.h"
+#include "core/loader/cache/ImageResourceClient.h"
 #include "core/page/Frame.h"
 #include "core/platform/graphics/Image.h"
 
@@ -39,16 +39,16 @@
 
 namespace WebCore {
 
-class MockCachedImageClient : public WebCore::CachedImageClient {
+class MockImageResourceClient : public WebCore::ImageResourceClient {
 public:
-    MockCachedImageClient()
+    MockImageResourceClient()
         : m_imageChangedCount(0)
         , m_notifyFinishedCalled(false)
     {
     }
 
-    virtual ~MockCachedImageClient() { }
-    virtual void imageChanged(CachedImage*, const IntRect*)
+    virtual ~MockImageResourceClient() { }
+    virtual void imageChanged(ImageResource*, const IntRect*)
     {
         m_imageChangedCount++;
     }
@@ -69,4 +69,4 @@
 
 } // namespace WebCore
 
-#endif // CachedImageTest_h
+#endif // ImageResourceTest_h
diff --git a/Source/core/loader/cache/CachedRawResource.cpp b/Source/core/loader/cache/RawResource.cpp
similarity index 76%
rename from Source/core/loader/cache/CachedRawResource.cpp
rename to Source/core/loader/cache/RawResource.cpp
index 4a1013e..a2a0dc4 100644
--- a/Source/core/loader/cache/CachedRawResource.cpp
+++ b/Source/core/loader/cache/RawResource.cpp
@@ -24,7 +24,7 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/CachedRawResource.h"
+#include "core/loader/cache/RawResource.h"
 
 #include "core/loader/ResourceLoader.h"
 #include "core/loader/cache/ResourceClient.h"
@@ -34,30 +34,30 @@
 
 namespace WebCore {
 
-CachedRawResource::CachedRawResource(const ResourceRequest& resourceRequest, Type type)
+RawResource::RawResource(const ResourceRequest& resourceRequest, Type type)
     : Resource(resourceRequest, type)
 {
 }
 
-void CachedRawResource::appendData(const char* data, int length)
+void RawResource::appendData(const char* data, int length)
 {
     Resource::appendData(data, length);
 
-    ResourcePtr<CachedRawResource> protect(this);
-    ResourceClientWalker<CachedRawResourceClient> w(m_clients);
-    while (CachedRawResourceClient* c = w.next())
+    ResourcePtr<RawResource> protect(this);
+    ResourceClientWalker<RawResourceClient> w(m_clients);
+    while (RawResourceClient* c = w.next())
         c->dataReceived(this, data, length);
 }
 
-void CachedRawResource::didAddClient(ResourceClient* c)
+void RawResource::didAddClient(ResourceClient* c)
 {
     if (!hasClient(c))
         return;
     // The calls to the client can result in events running, potentially causing
     // this resource to be evicted from the cache and all clients to be removed,
     // so a protector is necessary.
-    ResourcePtr<CachedRawResource> protect(this);
-    CachedRawResourceClient* client = static_cast<CachedRawResourceClient*>(c);
+    ResourcePtr<RawResource> protect(this);
+    RawResourceClient* client = static_cast<RawResourceClient*>(c);
     size_t redirectCount = m_redirectChain.size();
     for (size_t i = 0; i < redirectCount; i++) {
         RedirectPair redirect = m_redirectChain[i];
@@ -75,52 +75,52 @@
     if (m_data)
         client->dataReceived(this, m_data->data(), m_data->size());
     if (!hasClient(c))
-       return;
+        return;
     Resource::didAddClient(client);
 }
 
-void CachedRawResource::willSendRequest(ResourceRequest& request, const ResourceResponse& response)
+void RawResource::willSendRequest(ResourceRequest& request, const ResourceResponse& response)
 {
-    ResourcePtr<CachedRawResource> protect(this);
+    ResourcePtr<RawResource> protect(this);
     if (!response.isNull()) {
-        ResourceClientWalker<CachedRawResourceClient> w(m_clients);
-        while (CachedRawResourceClient* c = w.next())
+        ResourceClientWalker<RawResourceClient> w(m_clients);
+        while (RawResourceClient* c = w.next())
             c->redirectReceived(this, request, response);
         m_redirectChain.append(RedirectPair(request, response));
     }
     Resource::willSendRequest(request, response);
 }
 
-void CachedRawResource::responseReceived(const ResourceResponse& response)
+void RawResource::responseReceived(const ResourceResponse& response)
 {
-    ResourcePtr<CachedRawResource> protect(this);
+    ResourcePtr<RawResource> protect(this);
     Resource::responseReceived(response);
-    ResourceClientWalker<CachedRawResourceClient> w(m_clients);
-    while (CachedRawResourceClient* c = w.next())
+    ResourceClientWalker<RawResourceClient> w(m_clients);
+    while (RawResourceClient* c = w.next())
         c->responseReceived(this, m_response);
 }
 
-void CachedRawResource::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
+void RawResource::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
 {
-    ResourceClientWalker<CachedRawResourceClient> w(m_clients);
-    while (CachedRawResourceClient* c = w.next())
+    ResourceClientWalker<RawResourceClient> w(m_clients);
+    while (RawResourceClient* c = w.next())
         c->dataSent(this, bytesSent, totalBytesToBeSent);
 }
 
-void CachedRawResource::didDownloadData(int dataLength)
+void RawResource::didDownloadData(int dataLength)
 {
-    ResourceClientWalker<CachedRawResourceClient> w(m_clients);
-    while (CachedRawResourceClient* c = w.next())
+    ResourceClientWalker<RawResourceClient> w(m_clients);
+    while (RawResourceClient* c = w.next())
         c->dataDownloaded(this, dataLength);
 }
 
-void CachedRawResource::setDefersLoading(bool defers)
+void RawResource::setDefersLoading(bool defers)
 {
     if (m_loader)
         m_loader->setDefersLoading(defers);
 }
 
-void CachedRawResource::setDataBufferingPolicy(DataBufferingPolicy dataBufferingPolicy)
+void RawResource::setDataBufferingPolicy(DataBufferingPolicy dataBufferingPolicy)
 {
     m_options.dataBufferingPolicy = dataBufferingPolicy;
     clear();
@@ -144,7 +144,7 @@
     return m_headers.contains(headerName);
 }
 
-bool CachedRawResource::canReuse(const ResourceRequest& newRequest) const
+bool RawResource::canReuse(const ResourceRequest& newRequest) const
 {
     if (m_options.dataBufferingPolicy == DoNotBufferData)
         return false;
@@ -187,7 +187,7 @@
     return true;
 }
 
-void CachedRawResource::clear()
+void RawResource::clear()
 {
     m_data.clear();
     setEncodedSize(0);
diff --git a/Source/core/loader/cache/CachedRawResource.h b/Source/core/loader/cache/RawResource.h
similarity index 87%
rename from Source/core/loader/cache/CachedRawResource.h
rename to Source/core/loader/cache/RawResource.h
index cffe138..05cf3f4 100644
--- a/Source/core/loader/cache/CachedRawResource.h
+++ b/Source/core/loader/cache/RawResource.h
@@ -20,22 +20,22 @@
     Boston, MA 02110-1301, USA.
 */
 
-#ifndef CachedRawResource_h
-#define CachedRawResource_h
+#ifndef RawResource_h
+#define RawResource_h
 
 #include "core/loader/cache/Resource.h"
 #include "core/loader/cache/ResourceClient.h"
 
 namespace WebCore {
-class CachedRawResourceCallback;
-class CachedRawResourceClient;
+class RawResourceCallback;
+class RawResourceClient;
 
-class CachedRawResource : public Resource {
+class RawResource : public Resource {
 public:
-    CachedRawResource(const ResourceRequest&, Type);
+    RawResource(const ResourceRequest&, Type);
 
     // FIXME: AssociatedURLLoader shouldn't be a DocumentThreadableLoader and therefore shouldn't
-    // use CachedRawResource. However, it is, and it needs to be able to defer loading.
+    // use RawResource. However, it is, and it needs to be able to defer loading.
     // This can be fixed by splitting CORS preflighting out of DocumentThreacableLoader.
     virtual void setDefersLoading(bool);
 
@@ -72,9 +72,9 @@
 };
 
 
-class CachedRawResourceClient : public ResourceClient {
+class RawResourceClient : public ResourceClient {
 public:
-    virtual ~CachedRawResourceClient() { }
+    virtual ~RawResourceClient() { }
     static ResourceClientType expectedType() { return RawResourceType; }
     virtual ResourceClientType resourceClientType() const { return expectedType(); }
 
@@ -87,4 +87,4 @@
 
 }
 
-#endif // CachedRawResource_h
+#endif // RawResource_h
diff --git a/Source/core/loader/cache/Resource.cpp b/Source/core/loader/cache/Resource.cpp
index caaccdf..ae832e1 100644
--- a/Source/core/loader/cache/Resource.cpp
+++ b/Source/core/loader/cache/Resource.cpp
@@ -390,7 +390,7 @@
     if (!hasClients() && inCache())
         memoryCache()->addToLiveResourcesSize(this);
 
-    if ((m_type == RawResource || m_type == MainResource) && !m_response.isNull() && !m_proxyResource) {
+    if ((m_type == Raw || m_type == MainResource) && !m_response.isNull() && !m_proxyResource) {
         // Certain resources (especially XHRs and main resources) do crazy things if an asynchronous load returns
         // synchronously (e.g., scripts may not have set all the state they need to handle the load).
         // Therefore, rather than immediately sending callbacks on a cache hit like other Resources,
@@ -443,7 +443,7 @@
 {
     if (!m_loader)
         return;
-    if (m_type == MainResource || m_type == RawResource)
+    if (m_type == MainResource || m_type == Raw)
         cancelTimerFired(&m_cancelTimer);
     else if (!m_cancelTimer.isActive())
         m_cancelTimer.startOneShot(0);
diff --git a/Source/core/loader/cache/Resource.h b/Source/core/loader/cache/Resource.h
index 8f241ff..dd092e3 100644
--- a/Source/core/loader/cache/Resource.h
+++ b/Source/core/loader/cache/Resource.h
@@ -59,17 +59,17 @@
 public:
     enum Type {
         MainResource,
-        ImageResource,
+        Image,
         CSSStyleSheet,
         Script,
-        FontResource,
-        RawResource,
-        SVGDocumentResource,
+        Font,
+        Raw,
+        SVGDocument,
         XSLStyleSheet,
         LinkPrefetch,
         LinkSubresource,
-        TextTrackResource,
-        ShaderResource,
+        TextTrack,
+        Shader,
         ImportResource
     };
 
@@ -154,7 +154,7 @@
         return type() == MainResource
             || type() == LinkPrefetch
             || type() == LinkSubresource
-            || type() == RawResource;
+            || type() == Raw;
     }
 
     void updateForAccess();
diff --git a/Source/core/loader/cache/ResourceFetcher.cpp b/Source/core/loader/cache/ResourceFetcher.cpp
index 30e43f5..28d7c8c 100644
--- a/Source/core/loader/cache/ResourceFetcher.cpp
+++ b/Source/core/loader/cache/ResourceFetcher.cpp
@@ -39,17 +39,17 @@
 #include "core/loader/PingLoader.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
-#include "core/loader/cache/CachedDocument.h"
-#include "core/loader/cache/CachedFont.h"
-#include "core/loader/cache/CachedImage.h"
-#include "core/loader/cache/CachedRawResource.h"
-#include "core/loader/cache/CachedScript.h"
-#include "core/loader/cache/CachedShader.h"
-#include "core/loader/cache/CachedTextTrack.h"
-#include "core/loader/cache/CachedXSLStyleSheet.h"
+#include "core/loader/cache/CSSStyleSheetResource.h"
+#include "core/loader/cache/DocumentResource.h"
 #include "core/loader/cache/FetchRequest.h"
+#include "core/loader/cache/FontResource.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/MemoryCache.h"
+#include "core/loader/cache/RawResource.h"
+#include "core/loader/cache/ScriptResource.h"
+#include "core/loader/cache/ShaderResource.h"
+#include "core/loader/cache/TextTrackResource.h"
+#include "core/loader/cache/XSLStyleSheetResource.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
@@ -57,6 +57,7 @@
 #include "core/page/ResourceTimingInfo.h"
 #include "core/page/Settings.h"
 #include "core/platform/Logging.h"
+#include "core/platform/chromium/TraceEvent.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebURL.h"
 #include "weborigin/SecurityOrigin.h"
@@ -71,31 +72,31 @@
 static Resource* createResource(Resource::Type type, const ResourceRequest& request, const String& charset)
 {
     switch (type) {
-    case Resource::ImageResource:
-        return new CachedImage(request);
+    case Resource::Image:
+        return new ImageResource(request);
     case Resource::CSSStyleSheet:
-        return new CachedCSSStyleSheet(request, charset);
+        return new CSSStyleSheetResource(request, charset);
     case Resource::Script:
-        return new CachedScript(request, charset);
-    case Resource::SVGDocumentResource:
-        return new CachedDocument(request, Resource::SVGDocumentResource);
-    case Resource::FontResource:
-        return new CachedFont(request);
-    case Resource::RawResource:
+        return new ScriptResource(request, charset);
+    case Resource::SVGDocument:
+        return new DocumentResource(request, Resource::SVGDocument);
+    case Resource::Font:
+        return new FontResource(request);
+    case Resource::Raw:
     case Resource::MainResource:
-        return new CachedRawResource(request, type);
+        return new RawResource(request, type);
     case Resource::XSLStyleSheet:
-        return new CachedXSLStyleSheet(request);
+        return new XSLStyleSheetResource(request);
     case Resource::LinkPrefetch:
         return new Resource(request, Resource::LinkPrefetch);
     case Resource::LinkSubresource:
         return new Resource(request, Resource::LinkSubresource);
-    case Resource::TextTrackResource:
-        return new CachedTextTrack(request);
-    case Resource::ShaderResource:
-        return new CachedShader(request);
+    case Resource::TextTrack:
+        return new TextTrackResource(request);
+    case Resource::Shader:
+        return new ShaderResource(request);
     case Resource::ImportResource:
-        return new CachedRawResource(request, type);
+        return new RawResource(request, type);
     }
 
     ASSERT_NOT_REACHED();
@@ -113,23 +114,23 @@
     case Resource::CSSStyleSheet:
         return ResourceLoadPriorityHigh;
     case Resource::Script:
-    case Resource::FontResource:
-    case Resource::RawResource:
+    case Resource::Font:
+    case Resource::Raw:
     case Resource::ImportResource:
         return ResourceLoadPriorityMedium;
-    case Resource::ImageResource:
+    case Resource::Image:
         return request.forPreload() ? ResourceLoadPriorityVeryLow : ResourceLoadPriorityLow;
     case Resource::XSLStyleSheet:
         return ResourceLoadPriorityHigh;
-    case Resource::SVGDocumentResource:
+    case Resource::SVGDocument:
         return ResourceLoadPriorityLow;
     case Resource::LinkPrefetch:
         return ResourceLoadPriorityVeryLow;
     case Resource::LinkSubresource:
         return ResourceLoadPriorityLow;
-    case Resource::TextTrackResource:
+    case Resource::TextTrack:
         return ResourceLoadPriorityLow;
-    case Resource::ShaderResource:
+    case Resource::Shader:
         return ResourceLoadPriorityMedium;
     }
     ASSERT_NOT_REACHED();
@@ -148,7 +149,7 @@
         return 0;
     ResourceResponse response(url, mimetype, data->size(), charset, String());
 
-    Resource* resource = createResource(Resource::ImageResource, request, charset);
+    Resource* resource = createResource(Resource::Image, request, charset);
     resource->responseReceived(response);
     // FIXME: AppendData causes an unnecessary memcpy.
     if (data->size())
@@ -200,12 +201,12 @@
     return 0;
 }
 
-ResourcePtr<CachedImage> ResourceFetcher::requestImage(FetchRequest& request)
+ResourcePtr<ImageResource> ResourceFetcher::requestImage(FetchRequest& request)
 {
     if (Frame* f = frame()) {
         if (f->loader()->pageDismissalEventBeingDispatched() != FrameLoader::NoDismissal) {
             KURL requestURL = request.resourceRequest().url();
-            if (requestURL.isValid() && canRequest(Resource::ImageResource, requestURL, request.options(), request.forPreload()))
+            if (requestURL.isValid() && canRequest(Resource::Image, requestURL, request.options(), request.forPreload()))
                 PingLoader::loadImage(f, requestURL);
             return 0;
         }
@@ -215,7 +216,7 @@
         preCacheDataURIImage(request);
 
     request.setDefer(clientDefersImage(request.resourceRequest().url()) ? FetchRequest::DeferredByClient : FetchRequest::NoDefer);
-    return static_cast<CachedImage*>(requestResource(Resource::ImageResource, request).get());
+    return static_cast<ImageResource*>(requestResource(Resource::Image, request).get());
 }
 
 void ResourceFetcher::preCacheDataURIImage(const FetchRequest& request)
@@ -230,58 +231,58 @@
         memoryCache()->add(resource);
 }
 
-ResourcePtr<CachedFont> ResourceFetcher::requestFont(FetchRequest& request)
+ResourcePtr<FontResource> ResourceFetcher::requestFont(FetchRequest& request)
 {
-    return static_cast<CachedFont*>(requestResource(Resource::FontResource, request).get());
+    return static_cast<FontResource*>(requestResource(Resource::Font, request).get());
 }
 
-ResourcePtr<CachedTextTrack> ResourceFetcher::requestTextTrack(FetchRequest& request)
+ResourcePtr<TextTrackResource> ResourceFetcher::requestTextTrack(FetchRequest& request)
 {
-    return static_cast<CachedTextTrack*>(requestResource(Resource::TextTrackResource, request).get());
+    return static_cast<TextTrackResource*>(requestResource(Resource::TextTrack, request).get());
 }
 
-ResourcePtr<CachedShader> ResourceFetcher::requestShader(FetchRequest& request)
+ResourcePtr<ShaderResource> ResourceFetcher::requestShader(FetchRequest& request)
 {
-    return static_cast<CachedShader*>(requestResource(Resource::ShaderResource, request).get());
+    return static_cast<ShaderResource*>(requestResource(Resource::Shader, request).get());
 }
 
-ResourcePtr<CachedRawResource> ResourceFetcher::requestImport(FetchRequest& request)
+ResourcePtr<RawResource> ResourceFetcher::requestImport(FetchRequest& request)
 {
-    return static_cast<CachedRawResource*>(requestResource(Resource::ImportResource, request).get());
+    return static_cast<RawResource*>(requestResource(Resource::ImportResource, request).get());
 }
 
-ResourcePtr<CachedCSSStyleSheet> ResourceFetcher::requestCSSStyleSheet(FetchRequest& request)
+ResourcePtr<CSSStyleSheetResource> ResourceFetcher::requestCSSStyleSheet(FetchRequest& request)
 {
-    return static_cast<CachedCSSStyleSheet*>(requestResource(Resource::CSSStyleSheet, request).get());
+    return static_cast<CSSStyleSheetResource*>(requestResource(Resource::CSSStyleSheet, request).get());
 }
 
-ResourcePtr<CachedCSSStyleSheet> ResourceFetcher::requestUserCSSStyleSheet(FetchRequest& request)
+ResourcePtr<CSSStyleSheetResource> ResourceFetcher::requestUserCSSStyleSheet(FetchRequest& request)
 {
     KURL url = MemoryCache::removeFragmentIdentifierIfNeeded(request.resourceRequest().url());
 
     if (Resource* existing = memoryCache()->resourceForURL(url)) {
         if (existing->type() == Resource::CSSStyleSheet)
-            return static_cast<CachedCSSStyleSheet*>(existing);
+            return static_cast<CSSStyleSheetResource*>(existing);
         memoryCache()->remove(existing);
     }
 
     request.setOptions(ResourceLoaderOptions(DoNotSendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType, DocumentContext));
-    return static_cast<CachedCSSStyleSheet*>(requestResource(Resource::CSSStyleSheet, request).get());
+    return static_cast<CSSStyleSheetResource*>(requestResource(Resource::CSSStyleSheet, request).get());
 }
 
-ResourcePtr<CachedScript> ResourceFetcher::requestScript(FetchRequest& request)
+ResourcePtr<ScriptResource> ResourceFetcher::requestScript(FetchRequest& request)
 {
-    return static_cast<CachedScript*>(requestResource(Resource::Script, request).get());
+    return static_cast<ScriptResource*>(requestResource(Resource::Script, request).get());
 }
 
-ResourcePtr<CachedXSLStyleSheet> ResourceFetcher::requestXSLStyleSheet(FetchRequest& request)
+ResourcePtr<XSLStyleSheetResource> ResourceFetcher::requestXSLStyleSheet(FetchRequest& request)
 {
-    return static_cast<CachedXSLStyleSheet*>(requestResource(Resource::XSLStyleSheet, request).get());
+    return static_cast<XSLStyleSheetResource*>(requestResource(Resource::XSLStyleSheet, request).get());
 }
 
-ResourcePtr<CachedDocument> ResourceFetcher::requestSVGDocument(FetchRequest& request)
+ResourcePtr<DocumentResource> ResourceFetcher::requestSVGDocument(FetchRequest& request)
 {
-    return static_cast<CachedDocument*>(requestResource(Resource::SVGDocumentResource, request).get());
+    return static_cast<DocumentResource*>(requestResource(Resource::SVGDocument, request).get());
 }
 
 ResourcePtr<Resource> ResourceFetcher::requestLinkResource(Resource::Type type, FetchRequest& request)
@@ -291,14 +292,14 @@
     return requestResource(type, request);
 }
 
-ResourcePtr<CachedRawResource> ResourceFetcher::requestRawResource(FetchRequest& request)
+ResourcePtr<RawResource> ResourceFetcher::requestRawResource(FetchRequest& request)
 {
-    return static_cast<CachedRawResource*>(requestResource(Resource::RawResource, request).get());
+    return static_cast<RawResource*>(requestResource(Resource::Raw, request).get());
 }
 
-ResourcePtr<CachedRawResource> ResourceFetcher::requestMainResource(FetchRequest& request)
+ResourcePtr<RawResource> ResourceFetcher::requestMainResource(FetchRequest& request)
 {
-    return static_cast<CachedRawResource*>(requestResource(Resource::MainResource, request).get());
+    return static_cast<RawResource*>(requestResource(Resource::MainResource, request).get());
 }
 
 bool ResourceFetcher::checkInsecureContent(Resource::Type type, const KURL& url) const
@@ -306,7 +307,7 @@
     switch (type) {
     case Resource::Script:
     case Resource::XSLStyleSheet:
-    case Resource::SVGDocumentResource:
+    case Resource::SVGDocument:
     case Resource::CSSStyleSheet:
     case Resource::ImportResource:
         // These resource can inject script into the current document (Script,
@@ -317,11 +318,11 @@
         }
 
         break;
-    case Resource::TextTrackResource:
-    case Resource::ShaderResource:
-    case Resource::RawResource:
-    case Resource::ImageResource:
-    case Resource::FontResource: {
+    case Resource::TextTrack:
+    case Resource::Shader:
+    case Resource::Raw:
+    case Resource::Image:
+    case Resource::Font: {
         // These resources can corrupt only the frame's pixels.
         if (Frame* f = frame()) {
             Frame* top = f->tree()->top();
@@ -356,24 +357,24 @@
     // any URL.
     switch (type) {
     case Resource::MainResource:
-    case Resource::ImageResource:
+    case Resource::Image:
     case Resource::CSSStyleSheet:
     case Resource::Script:
-    case Resource::FontResource:
-    case Resource::RawResource:
+    case Resource::Font:
+    case Resource::Raw:
     case Resource::LinkPrefetch:
     case Resource::LinkSubresource:
-    case Resource::TextTrackResource:
-    case Resource::ShaderResource:
+    case Resource::TextTrack:
+    case Resource::Shader:
     case Resource::ImportResource:
         // By default these types of resources can be loaded from any origin.
-        // FIXME: Are we sure about Resource::FontResource?
+        // FIXME: Are we sure about Resource::Font?
         if (options.requestOriginPolicy == RestrictToSameOrigin && !m_document->securityOrigin()->canRequest(url)) {
             printAccessDeniedMessage(url);
             return false;
         }
         break;
-    case Resource::SVGDocumentResource:
+    case Resource::SVGDocument:
     case Resource::XSLStyleSheet:
         if (!m_document->securityOrigin()->canRequest(url)) {
             printAccessDeniedMessage(url);
@@ -400,28 +401,28 @@
             }
         }
         break;
-    case Resource::ShaderResource:
+    case Resource::Shader:
         // Since shaders are referenced from CSS Styles use the same rules here.
     case Resource::CSSStyleSheet:
         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowStyleFromSource(url))
             return false;
         break;
-    case Resource::SVGDocumentResource:
-    case Resource::ImageResource:
+    case Resource::SVGDocument:
+    case Resource::Image:
         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowImageFromSource(url))
             return false;
         break;
-    case Resource::FontResource: {
+    case Resource::Font: {
         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowFontFromSource(url))
             return false;
         break;
     }
     case Resource::MainResource:
-    case Resource::RawResource:
+    case Resource::Raw:
     case Resource::LinkPrefetch:
     case Resource::LinkSubresource:
         break;
-    case Resource::TextTrackResource:
+    case Resource::TextTrack:
         // Cues aren't called out in the CPS spec yet, but they only work with a media element
         // so use the media policy.
         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowMediaFromSource(url))
@@ -453,8 +454,8 @@
         if (resource->options().requestOriginPolicy == PotentiallyCrossOriginEnabled
             && !m_document->securityOrigin()->canRequest(resource->response().url())
             && !resource->passesAccessControlCheck(m_document->securityOrigin(), error)) {
-            if (Frame* frame = this->frame())
-                frame->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Script from origin '" + SecurityOrigin::create(resource->response().url())->toString() + "' has been blocked from loading by Cross-Origin Resource Sharing policy: " + error);
+            if (frame() && frame()->document())
+                frame()->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Script from origin '" + SecurityOrigin::create(resource->response().url())->toString() + "' has been blocked from loading by Cross-Origin Resource Sharing policy: " + error);
             return false;
         }
 
@@ -592,14 +593,14 @@
     case Resource::Script:
         targetType = ResourceRequest::TargetIsScript;
         break;
-    case Resource::FontResource:
-        targetType = ResourceRequest::TargetIsFontResource;
+    case Resource::Font:
+        targetType = ResourceRequest::TargetIsFont;
         break;
-    case Resource::ImageResource:
+    case Resource::Image:
         targetType = ResourceRequest::TargetIsImage;
         break;
-    case Resource::ShaderResource:
-    case Resource::RawResource:
+    case Resource::Shader:
+    case Resource::Raw:
     case Resource::ImportResource:
         targetType = ResourceRequest::TargetIsSubresource;
         break;
@@ -609,10 +610,10 @@
     case Resource::LinkSubresource:
         targetType = ResourceRequest::TargetIsSubresource;
         break;
-    case Resource::TextTrackResource:
+    case Resource::TextTrack:
         targetType = ResourceRequest::TargetIsTextTrack;
         break;
-    case Resource::SVGDocumentResource:
+    case Resource::SVGDocument:
         targetType = ResourceRequest::TargetIsImage;
         break;
     default:
@@ -720,6 +721,7 @@
     memoryCache()->remove(resource);
     memoryCache()->add(newResource.get());
     storeResourceTimingInitiatorInformation(newResource, request);
+    TRACE_EVENT_ASYNC_BEGIN2("net", "Resource", newResource.get(), "url", newResource->url().string().ascii(), "priority", newResource->resourceRequest().priority());
     return newResource;
 }
 
@@ -734,6 +736,7 @@
 
     memoryCache()->add(resource.get());
     storeResourceTimingInitiatorInformation(resource, request);
+    TRACE_EVENT_ASYNC_BEGIN2("net", "Resource", resource.get(), "url", resource->url().string().ascii(), "priority", resource->resourceRequest().priority());
     return resource;
 }
 
@@ -772,13 +775,13 @@
     }
 
     // Do not load from cache if images are not enabled. The load for this image will be blocked
-    // in CachedImage::load.
+    // in ImageResource::load.
     if (FetchRequest::DeferredByClient == defer)
         return Reload;
 
     // Always use data uris.
     // FIXME: Extend this to non-images.
-    if (type == Resource::ImageResource && request.url().protocolIsData())
+    if (type == Resource::Image && request.url().protocolIsData())
         return Use;
 
     if (!existingResource->canReuse(request))
@@ -911,7 +914,7 @@
     DocumentResourceMap::iterator end = m_documentResources.end();
     for (DocumentResourceMap::iterator it = m_documentResources.begin(); it != end; ++it) {
         Resource* resource = it->value.get();
-        if (resource->type() == Resource::ImageResource && resource->stillNeedsLoad() && !clientDefersImage(resource->url()))
+        if (resource->type() == Resource::Image && resource->stillNeedsLoad() && !clientDefersImage(resource->url()))
             const_cast<Resource*>(resource)->load(this, defaultResourceOptions());
     }
 }
@@ -1066,6 +1069,7 @@
     ResourcePtr<Resource> resource = requestResource(type, request);
     if (!resource || (m_preloads && m_preloads->contains(resource.get())))
         return;
+    TRACE_EVENT_ASYNC_STEP0("net", "Resource", resource.get(), "Preload");
     resource->increasePreloadCount();
 
     if (!m_preloads)
@@ -1132,6 +1136,7 @@
 
 void ResourceFetcher::didFinishLoading(const Resource* resource, double finishTime, const ResourceLoaderOptions& options)
 {
+    TRACE_EVENT_ASYNC_END0("net", "Resource", resource);
     if (options.sendLoadCallbacks != SendCallbacks)
         return;
     if (FrameLoader* loader = frameLoader())
@@ -1140,12 +1145,14 @@
 
 void ResourceFetcher::didChangeLoadingPriority(const Resource* resource, ResourceLoadPriority loadPriority)
 {
+    TRACE_EVENT_ASYNC_STEP1("net", "Resource", resource, "ChangePriority", "priority", loadPriority);
     if (FrameLoader* loader = frameLoader())
         loader->client()->dispatchDidChangeResourcePriority(resource->identifier(), loadPriority);
 }
 
 void ResourceFetcher::didFailLoading(const Resource* resource, const ResourceError& error, const ResourceLoaderOptions& options)
 {
+    TRACE_EVENT_ASYNC_END0("net", "Resource", resource);
     if (options.sendLoadCallbacks != SendCallbacks)
         return;
     if (FrameLoader* loader = frameLoader())
@@ -1221,7 +1228,7 @@
 {
     if (!canRequest(resource->type(), request.url(), options))
         return false;
-    if (resource->type() == Resource::ImageResource && shouldDeferImageLoad(request.url()))
+    if (resource->type() == Resource::Image && shouldDeferImageLoad(request.url()))
         return false;
     return true;
 }
diff --git a/Source/core/loader/cache/ResourceFetcher.h b/Source/core/loader/cache/ResourceFetcher.h
index d7fb1b1..c2ffa7a 100644
--- a/Source/core/loader/cache/ResourceFetcher.h
+++ b/Source/core/loader/cache/ResourceFetcher.h
@@ -41,15 +41,15 @@
 
 namespace WebCore {
 
-class CachedCSSStyleSheet;
-class CachedDocument;
-class CachedFont;
-class CachedImage;
-class CachedRawResource;
-class CachedScript;
-class CachedShader;
-class CachedTextTrack;
-class CachedXSLStyleSheet;
+class CSSStyleSheetResource;
+class DocumentResource;
+class FontResource;
+class ImageResource;
+class RawResource;
+class ScriptResource;
+class ShaderResource;
+class TextTrackResource;
+class XSLStyleSheetResource;
 class Document;
 class DocumentLoader;
 class Frame;
@@ -78,19 +78,19 @@
     using RefCounted<ResourceFetcher>::ref;
     using RefCounted<ResourceFetcher>::deref;
 
-    ResourcePtr<CachedImage> requestImage(FetchRequest&);
-    ResourcePtr<CachedCSSStyleSheet> requestCSSStyleSheet(FetchRequest&);
-    ResourcePtr<CachedCSSStyleSheet> requestUserCSSStyleSheet(FetchRequest&);
-    ResourcePtr<CachedScript> requestScript(FetchRequest&);
-    ResourcePtr<CachedFont> requestFont(FetchRequest&);
-    ResourcePtr<CachedRawResource> requestRawResource(FetchRequest&);
-    ResourcePtr<CachedRawResource> requestMainResource(FetchRequest&);
-    ResourcePtr<CachedDocument> requestSVGDocument(FetchRequest&);
-    ResourcePtr<CachedXSLStyleSheet> requestXSLStyleSheet(FetchRequest&);
+    ResourcePtr<ImageResource> requestImage(FetchRequest&);
+    ResourcePtr<CSSStyleSheetResource> requestCSSStyleSheet(FetchRequest&);
+    ResourcePtr<CSSStyleSheetResource> requestUserCSSStyleSheet(FetchRequest&);
+    ResourcePtr<ScriptResource> requestScript(FetchRequest&);
+    ResourcePtr<FontResource> requestFont(FetchRequest&);
+    ResourcePtr<RawResource> requestRawResource(FetchRequest&);
+    ResourcePtr<RawResource> requestMainResource(FetchRequest&);
+    ResourcePtr<DocumentResource> requestSVGDocument(FetchRequest&);
+    ResourcePtr<XSLStyleSheetResource> requestXSLStyleSheet(FetchRequest&);
     ResourcePtr<Resource> requestLinkResource(Resource::Type, FetchRequest&);
-    ResourcePtr<CachedTextTrack> requestTextTrack(FetchRequest&);
-    ResourcePtr<CachedShader> requestShader(FetchRequest&);
-    ResourcePtr<CachedRawResource> requestImport(FetchRequest&);
+    ResourcePtr<TextTrackResource> requestTextTrack(FetchRequest&);
+    ResourcePtr<ShaderResource> requestShader(FetchRequest&);
+    ResourcePtr<RawResource> requestImport(FetchRequest&);
 
     // Logs an access denied message to the console for the specified URL.
     void printAccessDeniedMessage(const KURL&) const;
diff --git a/Source/core/loader/cache/ResourceFetcherTest.cpp b/Source/core/loader/cache/ResourceFetcherTest.cpp
index cc9ef59..977f519 100644
--- a/Source/core/loader/cache/ResourceFetcherTest.cpp
+++ b/Source/core/loader/cache/ResourceFetcherTest.cpp
@@ -60,8 +60,8 @@
     // Try to request a url. The request should fail, no resource should be returned,
     // and no resource should be present in the cache.
     FetchRequest fetchRequest = FetchRequest(ResourceRequest(testURL), FetchInitiatorInfo());
-    ResourcePtr<CachedImage> image = fetcher->requestImage(fetchRequest);
-    EXPECT_EQ(image.get(), static_cast<CachedImage*>(0));
+    ResourcePtr<ImageResource> image = fetcher->requestImage(fetchRequest);
+    EXPECT_EQ(image.get(), static_cast<ImageResource*>(0));
     EXPECT_EQ(memoryCache()->resourceForURL(testURL), static_cast<Resource*>(0));
 }
 
diff --git a/Source/core/loader/cache/CachedScript.cpp b/Source/core/loader/cache/ScriptResource.cpp
similarity index 85%
rename from Source/core/loader/cache/CachedScript.cpp
rename to Source/core/loader/cache/ScriptResource.cpp
index 58019d6..b6e9189 100644
--- a/Source/core/loader/cache/CachedScript.cpp
+++ b/Source/core/loader/cache/ScriptResource.cpp
@@ -25,7 +25,7 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/CachedScript.h"
+#include "core/loader/cache/ScriptResource.h"
 
 #include "core/loader/TextResourceDecoder.h"
 #include "core/platform/MIMETypeRegistry.h"
@@ -34,9 +34,9 @@
 
 namespace WebCore {
 
-CachedScript::CachedScript(const ResourceRequest& resourceRequest, const String& charset)
+ScriptResource::ScriptResource(const ResourceRequest& resourceRequest, const String& charset)
     : Resource(resourceRequest, Script)
-    , m_decoder(TextResourceDecoder::create(ASCIILiteral("application/javascript"), charset))
+    , m_decoder(TextResourceDecoder::create("application/javascript", charset))
 {
     DEFINE_STATIC_LOCAL(const AtomicString, acceptScript, ("*/*", AtomicString::ConstructFromLiteral));
 
@@ -46,26 +46,26 @@
     setAccept(acceptScript);
 }
 
-CachedScript::~CachedScript()
+ScriptResource::~ScriptResource()
 {
 }
 
-void CachedScript::setEncoding(const String& chs)
+void ScriptResource::setEncoding(const String& chs)
 {
     m_decoder->setEncoding(chs, TextResourceDecoder::EncodingFromHTTPHeader);
 }
 
-String CachedScript::encoding() const
+String ScriptResource::encoding() const
 {
     return m_decoder->encoding().name();
 }
 
-String CachedScript::mimeType() const
+String ScriptResource::mimeType() const
 {
     return extractMIMETypeFromMediaType(m_response.httpHeaderField("Content-Type")).lower();
 }
 
-const String& CachedScript::script()
+const String& ScriptResource::script()
 {
     ASSERT(!isPurgeable());
     ASSERT(isLoaded());
@@ -84,7 +84,7 @@
     return m_script.string();
 }
 
-bool CachedScript::mimeTypeAllowedByNosniff() const
+bool ScriptResource::mimeTypeAllowedByNosniff() const
 {
     return parseContentTypeOptionsHeader(m_response.httpHeaderField("X-Content-Type-Options")) != ContentTypeOptionsNosniff || MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType());
 }
diff --git a/Source/core/loader/cache/CachedScript.h b/Source/core/loader/cache/ScriptResource.h
similarity index 70%
rename from Source/core/loader/cache/CachedScript.h
rename to Source/core/loader/cache/ScriptResource.h
index 38b3bb1..02d90ca 100644
--- a/Source/core/loader/cache/CachedScript.h
+++ b/Source/core/loader/cache/ScriptResource.h
@@ -23,33 +23,33 @@
     pages from the web. It has a memory cache for these objects.
 */
 
-#ifndef CachedScript_h
-#define CachedScript_h
+#ifndef ScriptResource_h
+#define ScriptResource_h
 
 #include "core/loader/cache/Resource.h"
 
 namespace WebCore {
 
 class ResourceFetcher;
-    class TextResourceDecoder;
+class TextResourceDecoder;
 
-    class CachedScript : public Resource {
-    public:
-        CachedScript(const ResourceRequest&, const String& charset);
-        virtual ~CachedScript();
+class ScriptResource : public Resource {
+public:
+    ScriptResource(const ResourceRequest&, const String& charset);
+    virtual ~ScriptResource();
 
-        const String& script();
+    const String& script();
 
-        virtual void setEncoding(const String&);
-        virtual String encoding() const;
-        String mimeType() const;
+    virtual void setEncoding(const String&);
+    virtual String encoding() const;
+    String mimeType() const;
 
-        bool mimeTypeAllowedByNosniff() const;
+    bool mimeTypeAllowedByNosniff() const;
 
-    private:
-        AtomicString m_script;
-        RefPtr<TextResourceDecoder> m_decoder;
-    };
+private:
+    AtomicString m_script;
+    RefPtr<TextResourceDecoder> m_decoder;
+};
 }
 
 #endif
diff --git a/Source/core/loader/cache/CachedShader.cpp b/Source/core/loader/cache/ShaderResource.cpp
similarity index 88%
rename from Source/core/loader/cache/CachedShader.cpp
rename to Source/core/loader/cache/ShaderResource.cpp
index 7ccc6b9..ec60ae1 100644
--- a/Source/core/loader/cache/CachedShader.cpp
+++ b/Source/core/loader/cache/ShaderResource.cpp
@@ -28,7 +28,7 @@
  */
 
 #include "config.h"
-#include "core/loader/cache/CachedShader.h"
+#include "core/loader/cache/ShaderResource.h"
 
 #include "core/loader/TextResourceDecoder.h"
 #include "core/platform/SharedBuffer.h"
@@ -36,17 +36,17 @@
 
 namespace WebCore {
 
-CachedShader::CachedShader(const ResourceRequest& resourceRequest)
-    : Resource(resourceRequest, ShaderResource)
+ShaderResource::ShaderResource(const ResourceRequest& resourceRequest)
+    : Resource(resourceRequest, Shader)
     , m_decoder(TextResourceDecoder::create("application/shader"))
 {
 }
 
-CachedShader::~CachedShader()
+ShaderResource::~ShaderResource()
 {
 }
 
-const String& CachedShader::shaderString()
+const String& ShaderResource::shaderString()
 {
     if (m_shaderString.isNull() && m_data) {
         StringBuilder builder;
diff --git a/Source/core/loader/cache/CachedShader.h b/Source/core/loader/cache/ShaderResource.h
similarity index 88%
rename from Source/core/loader/cache/CachedShader.h
rename to Source/core/loader/cache/ShaderResource.h
index f88c942..f7d2ffe 100644
--- a/Source/core/loader/cache/CachedShader.h
+++ b/Source/core/loader/cache/ShaderResource.h
@@ -27,8 +27,8 @@
  * SUCH DAMAGE.
  */
 
-#ifndef CachedShader_h
-#define CachedShader_h
+#ifndef ShaderResource_h
+#define ShaderResource_h
 
 #include "core/loader/cache/Resource.h"
 
@@ -36,10 +36,10 @@
 
 class TextResourceDecoder;
 
-class CachedShader : public Resource {
+class ShaderResource : public Resource {
 public:
-    CachedShader(const ResourceRequest&);
-    virtual ~CachedShader();
+    ShaderResource(const ResourceRequest&);
+    virtual ~ShaderResource();
 
     const String& shaderString();
 
@@ -51,4 +51,4 @@
 }
 
 
-#endif // CachedShader_h
+#endif // ShaderResource_h
diff --git a/Source/core/loader/cache/CachedStyleSheetClient.h b/Source/core/loader/cache/StyleSheetResourceClient.h
similarity index 83%
rename from Source/core/loader/cache/CachedStyleSheetClient.h
rename to Source/core/loader/cache/StyleSheetResourceClient.h
index ffe9d5d..02dc5bc 100644
--- a/Source/core/loader/cache/CachedStyleSheetClient.h
+++ b/Source/core/loader/cache/StyleSheetResourceClient.h
@@ -23,24 +23,24 @@
  pages from the web. It has a memory cache for these objects.
  */
 
-#ifndef CachedStyleSheetClient_h
-#define CachedStyleSheetClient_h
+#ifndef StyleSheetResourceClient_h
+#define StyleSheetResourceClient_h
 
 #include "core/loader/cache/ResourceClient.h"
 #include "weborigin/KURL.h"
 #include "wtf/Forward.h"
 
 namespace WebCore {
-class CachedCSSStyleSheet;
+class CSSStyleSheetResource;
 
-class CachedStyleSheetClient : public ResourceClient {
+class StyleSheetResourceClient : public ResourceClient {
 public:
-    virtual ~CachedStyleSheetClient() { }
+    virtual ~StyleSheetResourceClient() { }
     static ResourceClientType expectedType() { return StyleSheetType; }
     virtual ResourceClientType resourceClientType() const { return expectedType(); }
-    virtual void setCSSStyleSheet(const String& /* href */, const KURL& /* baseURL */, const String& /* charset */, const CachedCSSStyleSheet*) { }
+    virtual void setCSSStyleSheet(const String& /* href */, const KURL& /* baseURL */, const String& /* charset */, const CSSStyleSheetResource*) { }
     virtual void setXSLStyleSheet(const String& /* href */, const KURL& /* baseURL */, const String& /* sheet */) { }
 };
 }
 
-#endif // CachedStyleSheetClient_h
+#endif // StyleSheetResourceClient_h
diff --git a/Source/core/loader/cache/CachedTextTrack.cpp b/Source/core/loader/cache/TextTrackResource.cpp
similarity index 85%
rename from Source/core/loader/cache/CachedTextTrack.cpp
rename to Source/core/loader/cache/TextTrackResource.cpp
index 4f075f0..cf5e4a1 100644
--- a/Source/core/loader/cache/CachedTextTrack.cpp
+++ b/Source/core/loader/cache/TextTrackResource.cpp
@@ -25,23 +25,23 @@
 
 #include "config.h"
 
-#include "core/loader/cache/CachedTextTrack.h"
+#include "core/loader/cache/TextTrackResource.h"
 
 #include "core/loader/cache/ResourceClient.h"
 #include "core/loader/cache/ResourceClientWalker.h"
 
 namespace WebCore {
 
-CachedTextTrack::CachedTextTrack(const ResourceRequest& resourceRequest)
-    : Resource(resourceRequest, TextTrackResource)
+TextTrackResource::TextTrackResource(const ResourceRequest& resourceRequest)
+    : Resource(resourceRequest, TextTrack)
 {
 }
 
-CachedTextTrack::~CachedTextTrack()
+TextTrackResource::~TextTrackResource()
 {
 }
 
-void CachedTextTrack::appendData(const char* data, int length)
+void TextTrackResource::appendData(const char* data, int length)
 {
     Resource::appendData(data, length);
     ResourceClientWalker<ResourceClient> walker(m_clients);
diff --git a/Source/core/loader/cache/CachedTextTrack.h b/Source/core/loader/cache/TextTrackResource.h
similarity index 88%
rename from Source/core/loader/cache/CachedTextTrack.h
rename to Source/core/loader/cache/TextTrackResource.h
index fc6e45f..c3c0eba 100644
--- a/Source/core/loader/cache/CachedTextTrack.h
+++ b/Source/core/loader/cache/TextTrackResource.h
@@ -23,17 +23,17 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CachedTextTrack_h
-#define CachedTextTrack_h
+#ifndef TextTrackResource_h
+#define TextTrackResource_h
 
 #include "core/loader/cache/Resource.h"
 
 namespace WebCore {
 
-class CachedTextTrack : public Resource {
+class TextTrackResource : public Resource {
 public:
-    CachedTextTrack(const ResourceRequest&);
-    virtual ~CachedTextTrack();
+    TextTrackResource(const ResourceRequest&);
+    virtual ~TextTrackResource();
 
     virtual void appendData(const char*, int) OVERRIDE;
 };
diff --git a/Source/core/loader/cache/CachedXSLStyleSheet.cpp b/Source/core/loader/cache/XSLStyleSheetResource.cpp
similarity index 76%
rename from Source/core/loader/cache/CachedXSLStyleSheet.cpp
rename to Source/core/loader/cache/XSLStyleSheetResource.cpp
index d831488..9d9a014 100644
--- a/Source/core/loader/cache/CachedXSLStyleSheet.cpp
+++ b/Source/core/loader/cache/XSLStyleSheetResource.cpp
@@ -25,17 +25,17 @@
 */
 
 #include "config.h"
-#include "core/loader/cache/CachedXSLStyleSheet.h"
+#include "core/loader/cache/XSLStyleSheetResource.h"
 
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/CachedStyleSheetClient.h"
 #include "core/loader/cache/ResourceClientWalker.h"
+#include "core/loader/cache/StyleSheetResourceClient.h"
 #include "core/platform/SharedBuffer.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
-CachedXSLStyleSheet::CachedXSLStyleSheet(const ResourceRequest& resourceRequest)
+XSLStyleSheetResource::XSLStyleSheetResource(const ResourceRequest& resourceRequest)
     : Resource(resourceRequest, XSLStyleSheet)
     , m_decoder(TextResourceDecoder::create("text/xsl"))
 {
@@ -46,32 +46,32 @@
     setAccept(acceptXSLT);
 }
 
-void CachedXSLStyleSheet::didAddClient(ResourceClient* c)
+void XSLStyleSheetResource::didAddClient(ResourceClient* c)
 {
-    ASSERT(c->resourceClientType() == CachedStyleSheetClient::expectedType());
+    ASSERT(c->resourceClientType() == StyleSheetResourceClient::expectedType());
     if (!isLoading())
-        static_cast<CachedStyleSheetClient*>(c)->setXSLStyleSheet(m_resourceRequest.url(), m_response.url(), m_sheet);
+        static_cast<StyleSheetResourceClient*>(c)->setXSLStyleSheet(m_resourceRequest.url(), m_response.url(), m_sheet);
 }
 
-void CachedXSLStyleSheet::setEncoding(const String& chs)
+void XSLStyleSheetResource::setEncoding(const String& chs)
 {
     m_decoder->setEncoding(chs, TextResourceDecoder::EncodingFromHTTPHeader);
 }
 
-String CachedXSLStyleSheet::encoding() const
+String XSLStyleSheetResource::encoding() const
 {
     return m_decoder->encoding().name();
 }
 
-void CachedXSLStyleSheet::checkNotify()
+void XSLStyleSheetResource::checkNotify()
 {
     if (m_data.get()) {
         m_sheet = m_decoder->decode(m_data->data(), encodedSize());
         m_sheet.append(m_decoder->flush());
     }
 
-    ResourceClientWalker<CachedStyleSheetClient> w(m_clients);
-    while (CachedStyleSheetClient* c = w.next())
+    ResourceClientWalker<StyleSheetResourceClient> w(m_clients);
+    while (StyleSheetResourceClient* c = w.next())
         c->setXSLStyleSheet(m_resourceRequest.url(), m_response.url(), m_sheet);
 }
 
diff --git a/Source/core/loader/cache/CachedXSLStyleSheet.h b/Source/core/loader/cache/XSLStyleSheetResource.h
similarity index 71%
rename from Source/core/loader/cache/CachedXSLStyleSheet.h
rename to Source/core/loader/cache/XSLStyleSheetResource.h
index 93cbf44..4cab515 100644
--- a/Source/core/loader/cache/CachedXSLStyleSheet.h
+++ b/Source/core/loader/cache/XSLStyleSheetResource.h
@@ -23,32 +23,32 @@
     pages from the web. It has a memory cache for these objects.
 */
 
-#ifndef CachedXSLStyleSheet_h
-#define CachedXSLStyleSheet_h
+#ifndef XSLStyleSheetResource_h
+#define XSLStyleSheetResource_h
 
 #include "core/loader/cache/Resource.h"
 
 namespace WebCore {
 
 class ResourceFetcher;
-    class TextResourceDecoder;
+class TextResourceDecoder;
 
-    class CachedXSLStyleSheet : public Resource {
-    public:
-        CachedXSLStyleSheet(const ResourceRequest&);
+class XSLStyleSheetResource : public Resource {
+public:
+    XSLStyleSheetResource(const ResourceRequest&);
 
-        const String& sheet() const { return m_sheet; }
+    const String& sheet() const { return m_sheet; }
 
-        virtual void didAddClient(ResourceClient*);
-        virtual void setEncoding(const String&);
-        virtual String encoding() const;
+    virtual void didAddClient(ResourceClient*);
+    virtual void setEncoding(const String&);
+    virtual String encoding() const;
 
-    protected:
-        virtual void checkNotify();
+protected:
+    virtual void checkNotify();
 
-        String m_sheet;
-        RefPtr<TextResourceDecoder> m_decoder;
-    };
+    String m_sheet;
+    RefPtr<TextResourceDecoder> m_decoder;
+};
 
 } // namespace WebCore
 
diff --git a/Source/core/page/Console.idl b/Source/core/page/Console.idl
index f675e8e..d5373ca 100644
--- a/Source/core/page/Console.idl
+++ b/Source/core/page/Console.idl
@@ -41,7 +41,7 @@
     [CallWith=ScriptArguments&ScriptState] void trace();
     [CallWith=ScriptArguments&ScriptState, ImplementedAs=assertCondition] void assert([Default=Undefined] optional boolean condition);
     [CallWith=ScriptArguments&ScriptState] void count();
-    [CallWith=ScriptArguments] void markTimeline();
+    [DeprecateAs=ConsoleMarkTimeline, CallWith=ScriptArguments] void markTimeline();
 
     [CallWith=ScriptState] void profile([Default=NullString] optional DOMString title);
     [CallWith=ScriptState] void profileEnd([Default=NullString] optional DOMString title);
diff --git a/Source/core/page/ContentSecurityPolicy.cpp b/Source/core/page/ContentSecurityPolicy.cpp
index 6b88362..e03b6bb 100644
--- a/Source/core/page/ContentSecurityPolicy.cpp
+++ b/Source/core/page/ContentSecurityPolicy.cpp
@@ -521,7 +521,7 @@
 //
 bool CSPSourceList::parseNonce(const UChar* begin, const UChar* end, String& nonce)
 {
-    DEFINE_STATIC_LOCAL(const String, noncePrefix, (ASCIILiteral("'nonce-")));
+    DEFINE_STATIC_LOCAL(const String, noncePrefix, ("'nonce-"));
 
     if (!equalIgnoringCase(noncePrefix.characters8(), begin, noncePrefix.length()))
         return true;
@@ -1048,7 +1048,7 @@
 
 bool CSPDirectiveList::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
-    DEFINE_STATIC_LOCAL(String, consoleMessage, (ASCIILiteral("Refused to execute JavaScript URL because it violates the following Content Security Policy directive: ")));
+    DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute JavaScript URL because it violates the following Content Security Policy directive: "));
     if (reportingStatus == ContentSecurityPolicy::SendReport) {
         return checkInlineAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, contextURL, contextLine, true);
     } else {
@@ -1058,7 +1058,7 @@
 
 bool CSPDirectiveList::allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
-    DEFINE_STATIC_LOCAL(String, consoleMessage, (ASCIILiteral("Refused to execute inline event handler because it violates the following Content Security Policy directive: ")));
+    DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute inline event handler because it violates the following Content Security Policy directive: "));
     if (reportingStatus == ContentSecurityPolicy::SendReport) {
         return checkInlineAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, contextURL, contextLine, true);
     } else {
@@ -1068,7 +1068,7 @@
 
 bool CSPDirectiveList::allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
-    DEFINE_STATIC_LOCAL(String, consoleMessage, (ASCIILiteral("Refused to execute inline script because it violates the following Content Security Policy directive: ")));
+    DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute inline script because it violates the following Content Security Policy directive: "));
     return reportingStatus == ContentSecurityPolicy::SendReport ?
         checkInlineAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, contextURL, contextLine, true) :
         checkInline(operativeDirective(m_scriptSrc.get()));
@@ -1076,7 +1076,7 @@
 
 bool CSPDirectiveList::allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
-    DEFINE_STATIC_LOCAL(String, consoleMessage, (ASCIILiteral("Refused to apply inline style because it violates the following Content Security Policy directive: ")));
+    DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to apply inline style because it violates the following Content Security Policy directive: "));
     return reportingStatus == ContentSecurityPolicy::SendReport ?
         checkInlineAndReportViolation(operativeDirective(m_styleSrc.get()), consoleMessage, contextURL, contextLine, false) :
         checkInline(operativeDirective(m_styleSrc.get()));
@@ -1084,7 +1084,7 @@
 
 bool CSPDirectiveList::allowEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
-    DEFINE_STATIC_LOCAL(String, consoleMessage, (ASCIILiteral("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: ")));
+    DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "));
 
     return reportingStatus == ContentSecurityPolicy::SendReport ?
         checkEvalAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, String(), WTF::OrdinalNumber::beforeFirst(), state) :
@@ -1464,7 +1464,9 @@
         // header1,header2 OR header1
         //        ^                  ^
         OwnPtr<CSPDirectiveList> policy = CSPDirectiveList::create(this, begin, position, type);
-        if (!policy->isReportOnly() && !policy->allowEval(0, SuppressReport))
+
+        // We disable 'eval()' even in the case of report-only policies, and rely on the check in the V8Initializer::codeGenerationCheckCallbackInMainThread callback to determine whether the call should execute or not.
+        if (!policy->allowEval(0, SuppressReport))
             m_scriptExecutionContext->disableEval(policy->evalDisabledErrorMessage());
 
         m_policies.append(policy.release());
@@ -1723,7 +1725,7 @@
     }
 }
 
-void ContentSecurityPolicy::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header, const String& contextURL, const WTF::OrdinalNumber& contextLine, ScriptState* state) const
+void ContentSecurityPolicy::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header, const String& contextURL, const WTF::OrdinalNumber& contextLine, ScriptState* state)
 {
     logToConsole(consoleMessage, contextURL, contextLine, state);
 
@@ -1772,21 +1774,27 @@
 
     RefPtr<JSONObject> reportObject = JSONObject::create();
     reportObject->setObject("csp-report", cspReport.release());
+    String stringifiedReport = reportObject->toJSONString();
 
-    RefPtr<FormData> report = FormData::create(reportObject->toJSONString().utf8());
+    if (!shouldSendViolationReport(stringifiedReport))
+        return;
+
+    RefPtr<FormData> report = FormData::create(stringifiedReport.utf8());
 
     for (size_t i = 0; i < reportURIs.size(); ++i)
         PingLoader::sendViolationReport(frame, reportURIs[i], report, PingLoader::ContentSecurityPolicyViolationReport);
+
+    didSendViolationReport(stringifiedReport);
 }
 
 void ContentSecurityPolicy::reportUnsupportedDirective(const String& name) const
 {
-    DEFINE_STATIC_LOCAL(String, allow, (ASCIILiteral("allow")));
-    DEFINE_STATIC_LOCAL(String, options, (ASCIILiteral("options")));
-    DEFINE_STATIC_LOCAL(String, policyURI, (ASCIILiteral("policy-uri")));
-    DEFINE_STATIC_LOCAL(String, allowMessage, (ASCIILiteral("The 'allow' directive has been replaced with 'default-src'. Please use that directive instead, as 'allow' has no effect.")));
-    DEFINE_STATIC_LOCAL(String, optionsMessage, (ASCIILiteral("The 'options' directive has been replaced with 'unsafe-inline' and 'unsafe-eval' source expressions for the 'script-src' and 'style-src' directives. Please use those directives instead, as 'options' has no effect.")));
-    DEFINE_STATIC_LOCAL(String, policyURIMessage, (ASCIILiteral("The 'policy-uri' directive has been removed from the specification. Please specify a complete policy via the Content-Security-Policy header.")));
+    DEFINE_STATIC_LOCAL(String, allow, ("allow"));
+    DEFINE_STATIC_LOCAL(String, options, ("options"));
+    DEFINE_STATIC_LOCAL(String, policyURI, ("policy-uri"));
+    DEFINE_STATIC_LOCAL(String, allowMessage, ("The 'allow' directive has been replaced with 'default-src'. Please use that directive instead, as 'allow' has no effect."));
+    DEFINE_STATIC_LOCAL(String, optionsMessage, ("The 'options' directive has been replaced with 'unsafe-inline' and 'unsafe-eval' source expressions for the 'script-src' and 'style-src' directives. Please use those directives instead, as 'options' has no effect."));
+    DEFINE_STATIC_LOCAL(String, policyURIMessage, ("The 'policy-uri' directive has been removed from the specification. Please specify a complete policy via the Content-Security-Policy header."));
 
     String message = "Unrecognized Content-Security-Policy directive '" + name + "'.\n";
     if (equalIgnoringCase(name, allow))
@@ -1892,4 +1900,15 @@
     return false;
 }
 
+bool ContentSecurityPolicy::shouldSendViolationReport(const String& report) const
+{
+    // Collisions have no security impact, so we can save space by storing only the string's hash rather than the whole report.
+    return !m_violationReportsSent.contains(report.impl()->hash());
 }
+
+void ContentSecurityPolicy::didSendViolationReport(const String& report)
+{
+    m_violationReportsSent.add(report.impl()->hash());
+}
+
+} // namespace WebCore
diff --git a/Source/core/page/ContentSecurityPolicy.h b/Source/core/page/ContentSecurityPolicy.h
index 444455f..13f007f 100644
--- a/Source/core/page/ContentSecurityPolicy.h
+++ b/Source/core/page/ContentSecurityPolicy.h
@@ -27,8 +27,10 @@
 #define ContentSecurityPolicy_h
 
 #include "bindings/v8/ScriptState.h"
+#include "wtf/HashSet.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
+#include "wtf/text/StringHash.h"
 #include "wtf/text/TextPosition.h"
 #include "wtf/text/WTFString.h"
 
@@ -41,6 +43,7 @@
 class ContentSecurityPolicyResponseHeaders;
 class CSPDirectiveList;
 class DOMStringList;
+class JSONObject;
 class KURL;
 class ScriptExecutionContext;
 class SecurityOrigin;
@@ -125,7 +128,7 @@
     void reportInvalidReflectedXSS(const String&) const;
     void reportMissingReportURI(const String&) const;
     void reportUnsupportedDirective(const String&) const;
-    void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header, const String& contextURL = String(), const WTF::OrdinalNumber& contextLine = WTF::OrdinalNumber::beforeFirst(), ScriptState* = 0) const;
+    void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header, const String& contextURL = String(), const WTF::OrdinalNumber& contextLine = WTF::OrdinalNumber::beforeFirst(), ScriptState* = 0);
 
     void reportBlockedScriptExecutionToInspector(const String& directiveText) const;
 
@@ -145,9 +148,14 @@
     void logToConsole(const String& message, const String& contextURL = String(), const WTF::OrdinalNumber& contextLine = WTF::OrdinalNumber::beforeFirst(), ScriptState* = 0) const;
     void addPolicyFromHeaderValue(const String&, HeaderType);
 
+    bool shouldSendViolationReport(const String&) const;
+    void didSendViolationReport(const String&);
+
     ScriptExecutionContext* m_scriptExecutionContext;
     bool m_overrideInlineStyleAllowed;
     CSPDirectiveListVector m_policies;
+
+    HashSet<unsigned, AlreadyHashed> m_violationReportsSent;
 };
 
 }
diff --git a/Source/core/page/DOMWindowBase64.cpp b/Source/core/page/DOMWindowBase64.cpp
index c6ba45b..78c0ea1 100644
--- a/Source/core/page/DOMWindowBase64.cpp
+++ b/Source/core/page/DOMWindowBase64.cpp
@@ -47,7 +47,7 @@
         return String();
 
     if (!stringToEncode.containsOnlyLatin1()) {
-        es.throwDOMException(InvalidCharacterError);
+        es.throwDOMException(InvalidCharacterError, "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
         return String();
     }
 
@@ -60,13 +60,13 @@
         return String();
 
     if (!encodedString.containsOnlyLatin1()) {
-        es.throwDOMException(InvalidCharacterError);
+        es.throwDOMException(InvalidCharacterError, "'atob' failed: The string to be decoded contains characters outside of the Latin1 range.");
         return String();
     }
 
     Vector<char> out;
     if (!base64Decode(encodedString, out, Base64FailOnInvalidCharacter, Base64StrictPaddingValidation)) {
-        es.throwDOMException(InvalidCharacterError);
+        es.throwDOMException(InvalidCharacterError, "'atob' failed: The string to be decoded is not correctly encoded.");
         return String();
     }
 
diff --git a/Source/core/page/DiagnosticLoggingKeys.cpp b/Source/core/page/DiagnosticLoggingKeys.cpp
index 6e6db7e..690ddc6 100644
--- a/Source/core/page/DiagnosticLoggingKeys.cpp
+++ b/Source/core/page/DiagnosticLoggingKeys.cpp
@@ -30,67 +30,67 @@
 
 const String& DiagnosticLoggingKeys::mediaLoadedKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("mediaLoaded")));
+    DEFINE_STATIC_LOCAL(const String, key, ("mediaLoaded"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::mediaLoadingFailedKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("mediaFailedLoading")));
+    DEFINE_STATIC_LOCAL(const String, key, ("mediaFailedLoading"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::pluginLoadedKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("pluginLoaded")));
+    DEFINE_STATIC_LOCAL(const String, key, ("pluginLoaded"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::pluginLoadingFailedKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("pluginFailedLoading")));
+    DEFINE_STATIC_LOCAL(const String, key, ("pluginFailedLoading"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::pageContainsPluginKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("pageContainsPlugin")));
+    DEFINE_STATIC_LOCAL(const String, key, ("pageContainsPlugin"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::pageContainsAtLeastOnePluginKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("pageContainsAtLeastOnePlugin")));
+    DEFINE_STATIC_LOCAL(const String, key, ("pageContainsAtLeastOnePlugin"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::pageContainsMediaEngineKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("pageContainsMediaEngine")));
+    DEFINE_STATIC_LOCAL(const String, key, ("pageContainsMediaEngine"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::pageContainsAtLeastOneMediaEngineKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("pageContainsAtLeastOneMediaEngine")));
+    DEFINE_STATIC_LOCAL(const String, key, ("pageContainsAtLeastOneMediaEngine"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::passKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("pass")));
+    DEFINE_STATIC_LOCAL(const String, key, ("pass"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::failKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("fail")));
+    DEFINE_STATIC_LOCAL(const String, key, ("fail"));
     return key;
 }
 
 const String& DiagnosticLoggingKeys::noopKey()
 {
-    DEFINE_STATIC_LOCAL(const String, key, (ASCIILiteral("noop")));
+    DEFINE_STATIC_LOCAL(const String, key, ("noop"));
     return key;
 }
 
diff --git a/Source/core/page/DragController.cpp b/Source/core/page/DragController.cpp
index ccd92fa..f555825 100644
--- a/Source/core/page/DragController.cpp
+++ b/Source/core/page/DragController.cpp
@@ -50,7 +50,7 @@
 #include "core/html/HTMLPlugInElement.h"
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/page/DragActions.h"
 #include "core/page/DragClient.h"
@@ -661,7 +661,7 @@
     return (state.m_dragType & DragSourceActionSelection) ? startNode : 0;
 }
 
-static CachedImage* getCachedImage(Element* element)
+static ImageResource* getImageResource(Element* element)
 {
     ASSERT(element);
     RenderObject* renderer = element->renderer();
@@ -674,7 +674,7 @@
 static Image* getImage(Element* element)
 {
     ASSERT(element);
-    CachedImage* cachedImage = getCachedImage(element);
+    ImageResource* cachedImage = getImageResource(element);
     // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
     // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
     // which would be empty when asking the cached BitmapImages.
@@ -716,7 +716,7 @@
 
     if (state.m_dragType == DragSourceActionSelection) {
         if (enclosingTextFormControl(src->selection()->start())) {
-            clipboard->writePlainText(src->editor()->selectedTextForClipboard());
+            clipboard->writePlainText(src->selectedTextForClipboard());
         } else {
             RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
             ASSERT(selectionRange);
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index 559cc44..b6277bd 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -29,6 +29,7 @@
 #include "core/page/EventHandler.h"
 
 #include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Document.h"
@@ -54,7 +55,7 @@
 #include "core/html/HTMLFrameSetElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Chrome.h"
 #include "core/page/DragController.h"
 #include "core/page/DragState.h"
@@ -356,6 +357,7 @@
     m_maxMouseMovedDuration = 0;
     m_baseEventType = PlatformEvent::NoType;
     m_didStartDrag = false;
+    m_touchPressed = false;
 }
 
 void EventHandler::nodeWillBeRemoved(Node* nodeToBeRemoved)
@@ -381,7 +383,6 @@
 
 static VisibleSelection expandSelectionToRespectUserSelectAll(Node* targetNode, const VisibleSelection& selection)
 {
-#if ENABLE(USERSELECT_ALL)
     Node* rootUserSelectAll = Position::rootUserSelectAllForNode(targetNode);
     if (!rootUserSelectAll)
         return selection;
@@ -391,10 +392,6 @@
     newSelection.setExtent(positionAfterNode(rootUserSelectAll).downstream(CanCrossEditingBoundary));
 
     return newSelection;
-#else
-    UNUSED_PARAM(targetNode);
-    return selection;
-#endif
 }
 
 bool EventHandler::updateSelectionForMouseDownDispatchingSelectStart(Node* targetNode, const VisibleSelection& selection, TextGranularity granularity)
@@ -770,27 +767,27 @@
         newSelection = VisibleSelection(targetPosition);
     }
 
-#if ENABLE(USERSELECT_ALL)
-    Node* rootUserSelectAllForMousePressNode = Position::rootUserSelectAllForNode(m_mousePressNode.get());
-    if (rootUserSelectAllForMousePressNode && rootUserSelectAllForMousePressNode == Position::rootUserSelectAllForNode(target)) {
-        newSelection.setBase(positionBeforeNode(rootUserSelectAllForMousePressNode).upstream(CanCrossEditingBoundary));
-        newSelection.setExtent(positionAfterNode(rootUserSelectAllForMousePressNode).downstream(CanCrossEditingBoundary));
-    } else {
-        // Reset base for user select all when base is inside user-select-all area and extent < base.
-        if (rootUserSelectAllForMousePressNode && comparePositions(target->renderer()->positionForPoint(hitTestResult.localPoint()), m_mousePressNode->renderer()->positionForPoint(m_dragStartPos)) < 0)
-            newSelection.setBase(positionAfterNode(rootUserSelectAllForMousePressNode).downstream(CanCrossEditingBoundary));
+    if (RuntimeEnabledFeatures::userSelectAllEnabled()) {
+        Node* rootUserSelectAllForMousePressNode = Position::rootUserSelectAllForNode(m_mousePressNode.get());
+        if (rootUserSelectAllForMousePressNode && rootUserSelectAllForMousePressNode == Position::rootUserSelectAllForNode(target)) {
+            newSelection.setBase(positionBeforeNode(rootUserSelectAllForMousePressNode).upstream(CanCrossEditingBoundary));
+            newSelection.setExtent(positionAfterNode(rootUserSelectAllForMousePressNode).downstream(CanCrossEditingBoundary));
+        } else {
+            // Reset base for user select all when base is inside user-select-all area and extent < base.
+            if (rootUserSelectAllForMousePressNode && comparePositions(target->renderer()->positionForPoint(hitTestResult.localPoint()), m_mousePressNode->renderer()->positionForPoint(m_dragStartPos)) < 0)
+                newSelection.setBase(positionAfterNode(rootUserSelectAllForMousePressNode).downstream(CanCrossEditingBoundary));
 
-        Node* rootUserSelectAllForTarget = Position::rootUserSelectAllForNode(target);
-        if (rootUserSelectAllForTarget && m_mousePressNode->renderer() && comparePositions(target->renderer()->positionForPoint(hitTestResult.localPoint()), m_mousePressNode->renderer()->positionForPoint(m_dragStartPos)) < 0)
-            newSelection.setExtent(positionBeforeNode(rootUserSelectAllForTarget).upstream(CanCrossEditingBoundary));
-        else if (rootUserSelectAllForTarget && m_mousePressNode->renderer())
-            newSelection.setExtent(positionAfterNode(rootUserSelectAllForTarget).downstream(CanCrossEditingBoundary));
-        else
-            newSelection.setExtent(targetPosition);
+            Node* rootUserSelectAllForTarget = Position::rootUserSelectAllForNode(target);
+            if (rootUserSelectAllForTarget && m_mousePressNode->renderer() && comparePositions(target->renderer()->positionForPoint(hitTestResult.localPoint()), m_mousePressNode->renderer()->positionForPoint(m_dragStartPos)) < 0)
+                newSelection.setExtent(positionBeforeNode(rootUserSelectAllForTarget).upstream(CanCrossEditingBoundary));
+            else if (rootUserSelectAllForTarget && m_mousePressNode->renderer())
+                newSelection.setExtent(positionAfterNode(rootUserSelectAllForTarget).downstream(CanCrossEditingBoundary));
+            else
+                newSelection.setExtent(targetPosition);
+        }
+    } else {
+        newSelection.setExtent(targetPosition);
     }
-#else
-    newSelection.setExtent(targetPosition);
-#endif
 
     if (m_frame->selection()->granularity() != CharacterGranularity)
         newSelection.expandUsingGranularity(m_frame->selection()->granularity());
@@ -1146,7 +1143,7 @@
             StyleImage* styleImage = (*cursors)[i].image();
             if (!styleImage)
                 continue;
-            CachedImage* cachedImage = styleImage->cachedImage();
+            ImageResource* cachedImage = styleImage->cachedImage();
             if (!cachedImage)
                 continue;
             float scale = styleImage->imageScaleFactor();
@@ -1686,10 +1683,10 @@
 
     if (!m_frame->page())
         return false;
-    Frame* focusFrame = m_frame->page()->focusController()->focusedOrMainFrame();
+    Frame* focusFrame = m_frame->page()->focusController().focusedOrMainFrame();
     // Do not paste here if the focus was moved somewhere else.
     if (m_frame == focusFrame && m_frame->editor()->client()->supportsGlobalSelection())
-        return m_frame->editor()->command(ASCIILiteral("PasteGlobalSelection")).execute();
+        return m_frame->editor()->command("PasteGlobalSelection").execute();
 
     return false;
 }
@@ -2060,14 +2057,14 @@
         // clear swallowEvent if the page already set it (e.g., by canceling
         // default behavior).
         if (elementIsMouseFocusable) {
-            if (!page->focusController()->setFocusedElement(element, m_frame, FocusDirectionMouse))
+            if (!page->focusController().setFocusedElement(element, m_frame, FocusDirectionMouse))
                 swallowEvent = true;
         } else if (!element || !element->focused()) {
             // We call setFocusedElement even with !element in order to blur
             // current focus element when a link is clicked; this is expected by
             // some sites that rely on onChange handlers running from form
             // fields before the button click is processed.
-            if (!page->focusController()->setFocusedElement(0, m_frame))
+            if (!page->focusController().setFocusedElement(0, m_frame))
                 swallowEvent = true;
         }
     }
@@ -2858,7 +2855,7 @@
     if (!view)
         return;
 
-    if (!m_frame->page() || !m_frame->page()->focusController()->isActive())
+    if (!m_frame->page() || !m_frame->page()->focusController().isActive())
         return;
 
     // Don't dispatch a synthetic mouse move event if the mouse cursor is not visible to the user.
@@ -3010,13 +3007,13 @@
     if (initialKeyEvent.type() == PlatformEvent::RawKeyDown) {
         node->dispatchEvent(keydown, IGNORE_EXCEPTION);
         // If frame changed as a result of keydown dispatch, then return true to avoid sending a subsequent keypress message to the new frame.
-        bool changedFocusedFrame = m_frame->page() && m_frame != m_frame->page()->focusController()->focusedOrMainFrame();
+        bool changedFocusedFrame = m_frame->page() && m_frame != m_frame->page()->focusController().focusedOrMainFrame();
         return keydown->defaultHandled() || keydown->defaultPrevented() || changedFocusedFrame;
     }
 
     node->dispatchEvent(keydown, IGNORE_EXCEPTION);
     // If frame changed as a result of keydown dispatch, then return early to avoid sending a subsequent keypress message to the new frame.
-    bool changedFocusedFrame = m_frame->page() && m_frame != m_frame->page()->focusController()->focusedOrMainFrame();
+    bool changedFocusedFrame = m_frame->page() && m_frame != m_frame->page()->focusController().focusedOrMainFrame();
     bool keydownResult = keydown->defaultHandled() || keydown->defaultPrevented() || changedFocusedFrame;
     if (keydownResult)
         return keydownResult;
@@ -3413,7 +3410,7 @@
     if (m_frame->document()->inDesignMode())
         return;
 
-    if (page->focusController()->advanceFocus(focusDirection))
+    if (page->focusController().advanceFocus(focusDirection))
         event->setDefaultHandled();
 }
 
@@ -3437,7 +3434,7 @@
     if (m_frame->document()->inDesignMode())
         return;
 
-    if (page->focusController()->advanceFocus(focusDirection))
+    if (page->focusController().advanceFocus(focusDirection))
         event->setDefaultHandled();
 }
 
@@ -3833,7 +3830,7 @@
     Page* page = m_frame->page();
     if (!page)
         return;
-    page->focusController()->setFocusedFrame(m_frame);
+    page->focusController().setFocusedFrame(m_frame);
 }
 
 unsigned EventHandler::accessKeyModifiers()
diff --git a/Source/core/page/EventSource.cpp b/Source/core/page/EventSource.cpp
index 205cfaa..24b9608 100644
--- a/Source/core/page/EventSource.cpp
+++ b/Source/core/page/EventSource.cpp
@@ -75,13 +75,13 @@
 PassRefPtr<EventSource> EventSource::create(ScriptExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionState& es)
 {
     if (url.isEmpty()) {
-        es.throwDOMException(SyntaxError);
+        es.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
         return 0;
     }
 
     KURL fullURL = context->completeURL(url);
     if (!fullURL.isValid()) {
-        es.throwDOMException(SyntaxError);
+        es.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
         return 0;
     }
 
@@ -92,8 +92,7 @@
         shouldBypassMainWorldContentSecurityPolicy = document->frame()->script()->shouldBypassMainWorldContentSecurityPolicy();
     }
     if (!shouldBypassMainWorldContentSecurityPolicy && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
-        // FIXME: Should this be throwing an exception?
-        es.throwDOMException(SecurityError);
+        es.throwDOMException(SecurityError, "Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
         return 0;
     }
 
diff --git a/Source/core/page/EventSource.idl b/Source/core/page/EventSource.idl
index d92caa9..6aeade1 100644
--- a/Source/core/page/EventSource.idl
+++ b/Source/core/page/EventSource.idl
@@ -48,8 +48,8 @@
     readonly attribute unsigned short readyState;
 
     // networking
-    attribute EventListener onopen;
-    attribute EventListener onmessage;
-    attribute EventListener onerror;
+    attribute EventHandler onopen;
+    attribute EventHandler onmessage;
+    attribute EventHandler onerror;
     void close();
 };
diff --git a/Source/core/page/Frame.cpp b/Source/core/page/Frame.cpp
index ea914b5..a3e42b6 100644
--- a/Source/core/page/Frame.cpp
+++ b/Source/core/page/Frame.cpp
@@ -36,6 +36,7 @@
 #include "core/dom/Event.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
+#include "core/editing/InputMethodController.h"
 #include "core/editing/htmlediting.h"
 #include "core/editing/markup.h"
 #include "core/html/HTMLFrameElementBase.h"
@@ -50,6 +51,7 @@
 #include "core/page/FrameDestructionObserver.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
+#include "core/page/Settings.h"
 #include "core/page/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/DragImage.h"
@@ -106,6 +108,7 @@
     , m_selection(adoptPtr(new FrameSelection(this)))
     , m_eventHandler(adoptPtr(new EventHandler(this)))
     , m_animationController(adoptPtr(new AnimationController(this)))
+    , m_inputMethodController(InputMethodController::create(this))
     , m_pageZoomFactor(parentPageZoomFactor(this))
     , m_textZoomFactor(parentTextZoomFactor(this))
 #if ENABLE(ORIENTATION_EVENTS)
@@ -359,8 +362,8 @@
 
     // FIXME: It's unclear as to why this is called more than once, but it is,
     // so page() could be NULL.
-    if (page() && page()->focusController()->focusedFrame() == this)
-        page()->focusController()->setFocusedFrame(0);
+    if (page() && page()->focusController().focusedFrame() == this)
+        page()->focusController().setFocusedFrame(0);
 
     if (page() && page()->scrollingCoordinator() && m_view)
         page()->scrollingCoordinator()->willDestroyScrollableArea(m_view.get());
@@ -400,6 +403,16 @@
     return document() ? document()->displayStringModifiedByEncoding(str) : str;
 }
 
+String Frame::selectedText() const
+{
+    return selection()->selectedText();
+}
+
+String Frame::selectedTextForClipboard() const
+{
+    return selection()->selectedTextForClipboard();
+}
+
 VisiblePosition Frame::visiblePositionForPoint(const IntPoint& framePoint)
 {
     HitTestResult result = eventHandler()->hitTestResultAtPoint(framePoint);
diff --git a/Source/core/page/Frame.h b/Source/core/page/Frame.h
index f744f1c..47fdc5a 100644
--- a/Source/core/page/Frame.h
+++ b/Source/core/page/Frame.h
@@ -54,6 +54,7 @@
     class FrameView;
     class HTMLFrameOwnerElement;
     class HTMLTableCellElement;
+    class InputMethodController;
     class IntPoint;
     class Node;
     class Range;
@@ -100,6 +101,7 @@
         FrameSelection* selection() const;
         FrameTree* tree() const;
         AnimationController* animation() const;
+        InputMethodController& inputMethodController() const;
         ScriptController* script();
 
         RenderView* contentRenderer() const; // Root of the render tree for the document contained in this frame.
@@ -152,6 +154,9 @@
         PassOwnPtr<DragImage> nodeImage(Node*);
         PassOwnPtr<DragImage> dragImageForSelection();
 
+        String selectedText() const;
+        String selectedTextForClipboard() const;
+
         VisiblePosition visiblePositionForPoint(const IntPoint& framePoint);
         Document* documentAtPoint(const IntPoint& windowPoint);
         PassRefPtr<Range> rangeForPoint(const IntPoint& framePoint);
@@ -182,6 +187,7 @@
         OwnPtr<FrameSelection> m_selection;
         OwnPtr<EventHandler> m_eventHandler;
         OwnPtr<AnimationController> m_animationController;
+        OwnPtr<InputMethodController> m_inputMethodController;
 
         float m_pageZoomFactor;
         float m_textZoomFactor;
@@ -238,6 +244,11 @@
         return m_animationController.get();
     }
 
+    inline InputMethodController& Frame::inputMethodController() const
+    {
+        return *m_inputMethodController;
+    }
+
     inline HTMLFrameOwnerElement* Frame::ownerElement() const
     {
         return m_ownerElement;
diff --git a/Source/core/page/FrameView.cpp b/Source/core/page/FrameView.cpp
index c66d12c..72c0b02 100644
--- a/Source/core/page/FrameView.cpp
+++ b/Source/core/page/FrameView.cpp
@@ -883,7 +883,15 @@
             m_inSynchronousPostLayout = false;
         }
 
-        document->evaluateMediaQueryList();
+        // Viewport-dependent media queries may cause us to need completely different style information.
+        if (!document->styleResolverIfExists() || document->styleResolverIfExists()->affectedByViewportChange()) {
+            document->styleResolverChanged(DeferRecalcStyle);
+            // FIXME: This instrumentation event is not strictly accurate since cached media query results
+            //        do not persist across StyleResolver rebuilds.
+            InspectorInstrumentation::mediaQueryResultChanged(document);
+        } else {
+            document->evaluateMediaQueryList();
+        }
 
         // If there is any pagination to apply, it will affect the RenderView's style, so we should
         // take care of that now.
@@ -962,9 +970,9 @@
                     RenderBox* rootRenderer = document->documentElement() ? document->documentElement()->renderBox() : 0;
                     RenderBox* bodyRenderer = rootRenderer && document->body() ? document->body()->renderBox() : 0;
                     if (bodyRenderer && bodyRenderer->stretchesToViewport())
-                        bodyRenderer->setChildNeedsLayout(true);
+                        bodyRenderer->setChildNeedsLayout();
                     else if (rootRenderer && rootRenderer->stretchesToViewport())
-                        rootRenderer->setChildNeedsLayout(true);
+                        rootRenderer->setChildNeedsLayout();
                 }
             }
         }
@@ -1111,7 +1119,7 @@
     for (RenderLazyBlock* block = renderView()->firstLazyBlock(); block; block = block->next()) {
         if (!block->isNested())
             continue;
-        block->setNeedsLayout(true);
+        block->setNeedsLayout();
         layout();
     }
 }
@@ -1561,7 +1569,7 @@
     ViewportConstrainedObjectSet::const_iterator end = m_viewportConstrainedObjects->end();
     for (ViewportConstrainedObjectSet::const_iterator it = m_viewportConstrainedObjects->begin(); it != end; ++it) {
         RenderObject* renderer = *it;
-        renderer->setNeedsLayout(true);
+        renderer->setNeedsLayout();
     }
 }
 
@@ -1871,7 +1879,7 @@
     // When frame seamless is enabled, the contents of the frame could affect the layout of the parent frames.
     // Also invalidate parent frame starting from the owner element of this frame.
     if (m_frame->ownerRenderer() && frame()->document()->shouldDisplaySeamlesslyWithParent())
-        m_frame->ownerRenderer()->setNeedsLayout(true, MarkContainingBlockChain);
+        m_frame->ownerRenderer()->setNeedsLayout(MarkContainingBlockChain);
 
     int delay = m_frame->document()->minimumLayoutDelay();
     if (m_layoutTimer.isActive() && m_delayedLayout && !delay)
@@ -1962,7 +1970,7 @@
     }
 
     if (RenderView* renderView = this->renderView())
-        renderView->setNeedsLayout(true);
+        renderView->setNeedsLayout();
 }
 
 void FrameView::unscheduleRelayout()
@@ -2232,12 +2240,6 @@
 
     m_actionScheduler->resume();
 
-    // Viewport-dependent media queries may cause us to need completely different style information.
-    if (m_frame->document()->styleResolver()->affectedByViewportChange()) {
-        m_frame->document()->styleResolverChanged(DeferRecalcStyle);
-        InspectorInstrumentation::mediaQueryResultChanged(m_frame->document());
-    }
-
     // Refetch render view since it can be destroyed by updateWidget() call above.
     renderView = this->renderView();
     if (renderView && !renderView->printing()) {
@@ -2451,7 +2453,7 @@
 bool FrameView::isActive() const
 {
     Page* page = frame()->page();
-    return page && page->focusController()->isActive();
+    return page && page->focusController().isActive();
 }
 
 void FrameView::scrollTo(const IntSize& newOffset)
diff --git a/Source/core/page/History.cpp b/Source/core/page/History.cpp
index a02df7a..cbda2a6 100644
--- a/Source/core/page/History.cpp
+++ b/Source/core/page/History.cpp
@@ -139,33 +139,17 @@
     return KURL(baseURL, urlString);
 }
 
-void History::stateObjectAdded(PassRefPtr<SerializedScriptValue> data, const String& title, const String& urlString, StateObjectType stateObjectType, ExceptionState& es)
+void History::stateObjectAdded(PassRefPtr<SerializedScriptValue> data, const String& title, const String& urlString, SameDocumentNavigationSource sameDocumentNavigationSource, ExceptionState& es)
 {
     if (!m_frame || !m_frame->page())
         return;
 
     KURL fullURL = urlForState(urlString);
     if (!fullURL.isValid() || !m_frame->document()->securityOrigin()->canRequest(fullURL)) {
-        es.throwDOMException(SecurityError);
+        es.throwDOMException(SecurityError, "A history state object with URL '" + fullURL.elidedString() + "' cannot be created in a document with origin '" + m_frame->document()->securityOrigin()->toString() + "'.");
         return;
     }
-
-    if (stateObjectType == StateObjectPush)
-        m_frame->loader()->history()->pushState(data, title, fullURL.string());
-    else if (stateObjectType == StateObjectReplace)
-        m_frame->loader()->history()->replaceState(data, title, fullURL.string());
-
-    if (!urlString.isEmpty())
-        m_frame->document()->updateURLForPushOrReplaceState(fullURL);
-
-    if (m_frame->loader()->documentLoader()->wasOnloadHandled())
-        m_frame->loader()->client()->postProgressStartedNotification();
-    m_frame->loader()->documentLoader()->clearRedirectChain();
-    m_frame->loader()->documentLoader()->appendRedirect(fullURL);
-    m_frame->loader()->client()->dispatchDidNavigateWithinPage();
-
-    if (m_frame->loader()->documentLoader()->wasOnloadHandled())
-        m_frame->loader()->client()->postProgressFinishedNotification();
+    m_frame->loader()->updateForSameDocumentNavigation(fullURL, sameDocumentNavigationSource, data, title);
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/History.h b/Source/core/page/History.h
index 9c74eae..6bd9da7 100644
--- a/Source/core/page/History.h
+++ b/Source/core/page/History.h
@@ -28,6 +28,7 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "bindings/v8/SerializedScriptValue.h"
+#include "core/loader/FrameLoaderTypes.h"
 #include "core/page/DOMWindowProperty.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
@@ -57,11 +58,7 @@
     bool stateChanged() const;
     bool isSameAsCurrentState(SerializedScriptValue*) const;
 
-    enum StateObjectType {
-        StateObjectPush,
-        StateObjectReplace
-    };
-    void stateObjectAdded(PassRefPtr<SerializedScriptValue>, const String& title, const String& url, StateObjectType, ExceptionState&);
+    void stateObjectAdded(PassRefPtr<SerializedScriptValue>, const String& title, const String& url, SameDocumentNavigationSource, ExceptionState&);
 
 private:
     explicit History(Frame*);
diff --git a/Source/core/page/ImageBitmap.cpp b/Source/core/page/ImageBitmap.cpp
index 2f83dd3..ffe3af0 100644
--- a/Source/core/page/ImageBitmap.cpp
+++ b/Source/core/page/ImageBitmap.cpp
@@ -38,8 +38,9 @@
 {
     m_imageElement->addClient(this);
 
-    IntSize bitmapSize = intersection(cropRect, IntRect(0, 0, image->width(), image->height())).size();
-    m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), bitmapSize);
+    IntRect srcRect = intersection(cropRect, IntRect(0, 0, image->width(), image->height()));
+    m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
+    m_bitmapOffset = srcRect.location();
 
     ScriptWrappable::init(this);
 }
@@ -47,6 +48,7 @@
 ImageBitmap::ImageBitmap(HTMLVideoElement* video, const IntRect& cropRect)
     : m_cropRect(cropRect)
     , m_imageElement(0)
+    , m_bitmapOffset(IntPoint())
 {
     IntRect videoRect = IntRect(IntPoint(), video->player()->naturalSize());
     IntRect srcRect = intersection(cropRect, videoRect);
@@ -66,6 +68,7 @@
 ImageBitmap::ImageBitmap(HTMLCanvasElement* canvas, const IntRect& cropRect)
     : m_cropRect(cropRect)
     , m_imageElement(0)
+    , m_bitmapOffset(IntPoint())
 {
     IntSize canvasSize = canvas->size();
     IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), canvasSize));
@@ -82,6 +85,7 @@
 ImageBitmap::ImageBitmap(ImageData* data, const IntRect& cropRect)
     : m_cropRect(cropRect)
     , m_imageElement(0)
+    , m_bitmapOffset(IntPoint())
 {
     IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), data->size()));
 
@@ -98,14 +102,16 @@
 ImageBitmap::ImageBitmap(ImageBitmap* bitmap, const IntRect& cropRect)
     : m_cropRect(cropRect)
     , m_imageElement(bitmap->imageElement())
+    , m_bitmapOffset(IntPoint())
 {
     IntRect oldBitmapRect = bitmap->bitmapRect();
-    IntSize bitmapSize = intersection(cropRect, oldBitmapRect).size();
-    IntPoint bitmapOffset(max(0, oldBitmapRect.x() - cropRect.x()), max(0, oldBitmapRect.y() - cropRect.y()));
-    m_bitmapRect = IntRect(bitmapOffset, bitmapSize);
+    IntRect srcRect = intersection(cropRect, oldBitmapRect);
+    m_bitmapRect = IntRect(IntPoint(max(0, oldBitmapRect.x() - cropRect.x()), max(0, oldBitmapRect.y() - cropRect.y())), srcRect.size());
+
     if (m_imageElement) {
         m_imageElement->addClient(this);
         m_bitmap = 0;
+        m_bitmapOffset = srcRect.location();
     } else {
         IntRect adjustedCropRect(IntPoint(cropRect.x() -oldBitmapRect.x(), cropRect.y() - oldBitmapRect.y()), cropRect.size());
         m_bitmap = cropImage(bitmap->bitmapImage().get(), adjustedCropRect);
@@ -157,6 +163,7 @@
 void ImageBitmap::notifyImageSourceChanged()
 {
     m_bitmap = cropImage(m_imageElement->cachedImage()->image(), m_cropRect);
+    m_bitmapOffset = IntPoint();
     m_imageElement = 0;
 }
 
@@ -164,7 +171,7 @@
 {
     ASSERT((m_imageElement || m_bitmap) && (!m_imageElement || !m_bitmap));
     if (m_imageElement)
-        return cropImage(m_imageElement->cachedImage()->image(), m_cropRect);
+        return m_imageElement->cachedImage()->image();
     return m_bitmap;
 }
 
diff --git a/Source/core/page/ImageBitmap.h b/Source/core/page/ImageBitmap.h
index 102fa62..9ad5e76 100644
--- a/Source/core/page/ImageBitmap.h
+++ b/Source/core/page/ImageBitmap.h
@@ -32,12 +32,13 @@
     PassRefPtr<HTMLImageElement> imageElement() const { return m_imageElement; }
 
     IntRect bitmapRect() const { return m_bitmapRect; }
+    IntPoint bitmapOffset() const { return m_bitmapOffset; }
 
     int width() const { return m_cropRect.width(); }
     int height() const { return m_cropRect.height(); }
     IntSize size() const { return m_cropRect.size(); }
 
-    ~ImageBitmap();
+    virtual ~ImageBitmap();
 
 private:
     ImageBitmap(HTMLImageElement*, const IntRect&);
@@ -58,6 +59,12 @@
 
     IntRect m_bitmapRect; // The rect where the underlying Image should be placed in reference to the ImageBitmap.
     IntRect m_cropRect;
+
+    // The offset by which the desired Image is stored internally.
+    // ImageBitmaps constructed from HTMLImageElements reference the entire ImageResource and may have a non-zero bitmap offset.
+    // ImageBitmaps not constructed from HTMLImageElements always pre-crop and store the image at (0, 0).
+    IntPoint m_bitmapOffset;
+
 };
 
 } // namespace WebCore
diff --git a/Source/core/page/ImageBitmapFactories.cpp b/Source/core/page/ImageBitmapFactories.cpp
index 9907616..a68e94e 100644
--- a/Source/core/page/ImageBitmapFactories.cpp
+++ b/Source/core/page/ImageBitmapFactories.cpp
@@ -49,7 +49,7 @@
 
 static LayoutSize sizeFor(HTMLImageElement* image)
 {
-    if (CachedImage* cachedImage = image->cachedImage())
+    if (ImageResource* cachedImage = image->cachedImage())
         return cachedImage->imageSizeForRenderer(image->renderer(), 1.0f); // FIXME: Not sure about this.
     return IntSize();
 }
diff --git a/Source/core/page/ImageBitmapTest.cpp b/Source/core/page/ImageBitmapTest.cpp
new file mode 100644
index 0000000..54c9247
--- /dev/null
+++ b/Source/core/page/ImageBitmapTest.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/page/ImageBitmap.h"
+
+#include "core/dom/Document.h"
+#include "core/html/HTMLImageElement.h"
+#include "core/loader/cache/ImageResource.h"
+#include "core/platform/graphics/BitmapImage.h"
+#include "core/platform/graphics/skia/NativeImageSkia.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+class ImageBitmapTest : public ::testing::Test {
+};
+
+// Verifies that the cached image held by an ImageBitmap is the same as the
+// one held by the HTMLImageElement.
+TEST_F(ImageBitmapTest, ImageResourceConsistency)
+{
+    SkBitmap bitmap;
+    bitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
+    bitmap.allocPixels();
+    int width = bitmap.width();
+    int height = bitmap.height();
+    for (int y = 0; y < height; ++y)
+        for (int x = 0; x < width; ++x)
+            *bitmap.getAddr32(x, y) = 0xFFFFFFFF;
+
+    RefPtr<HTMLImageElement> imageElement = HTMLImageElement::create(Document::create().get());
+    imageElement->setImageResource(new ImageResource(BitmapImage::create(NativeImageSkia::create(bitmap)).get()));
+
+    RefPtr<ImageBitmap> imageBitmapNoCrop = ImageBitmap::create(imageElement.get(), IntRect(0, 0, width, height));
+    RefPtr<ImageBitmap> imageBitmapInteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(width / 2, height / 2, width / 2, height / 2));
+    RefPtr<ImageBitmap> imageBitmapExteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(-width / 2, -height / 2, width, height));
+    RefPtr<ImageBitmap> imageBitmapOutsideImageRect = ImageBitmap::create(imageElement.get(), IntRect(-width, -height, width, height));
+
+    ASSERT_EQ(imageBitmapNoCrop->bitmapImage().get(), imageElement->cachedImage()->image());
+    ASSERT_EQ(imageBitmapInteriorCrop->bitmapImage().get(), imageElement->cachedImage()->image());
+    ASSERT_EQ(imageBitmapExteriorCrop->bitmapImage().get(), imageElement->cachedImage()->image());
+    ASSERT_EQ(imageBitmapOutsideImageRect->bitmapImage().get(), imageElement->cachedImage()->image());
+}
+
+} // namespace
diff --git a/Source/core/page/Page.h b/Source/core/page/Page.h
index 0edf04d..621e069 100644
--- a/Source/core/page/Page.h
+++ b/Source/core/page/Page.h
@@ -142,7 +142,7 @@
     Chrome& chrome() const { return *m_chrome; }
     DragCaretController* dragCaretController() const { return m_dragCaretController.get(); }
     DragController* dragController() const { return m_dragController.get(); }
-    FocusController* focusController() const { return m_focusController.get(); }
+    FocusController& focusController() const { return *m_focusController; }
     ContextMenuController* contextMenuController() const { return m_contextMenuController.get(); }
     InspectorController* inspectorController() const { return m_inspectorController.get(); }
     PointerLockController* pointerLockController() const { return m_pointerLockController.get(); }
diff --git a/Source/core/page/PageScaleConstraintsSet.cpp b/Source/core/page/PageScaleConstraintsSet.cpp
index a5df3e1..294a9be 100644
--- a/Source/core/page/PageScaleConstraintsSet.cpp
+++ b/Source/core/page/PageScaleConstraintsSet.cpp
@@ -111,7 +111,7 @@
         targetDPI = 240.0f;
     else if (arguments.deprecatedTargetDensityDPI != ViewportArguments::ValueAuto)
         targetDPI = arguments.deprecatedTargetDensityDPI;
-    return targetDPI > 0 ? (deviceScaleFactor * 120.0f) / targetDPI : 1.0f;
+    return targetDPI > 0 ? 160.0f / targetDPI : 1.0f;
 }
 
 static float getLayoutWidthForNonWideViewport(const FloatSize& deviceSize, float initialScale)
diff --git a/Source/core/page/PageSerializer.cpp b/Source/core/page/PageSerializer.cpp
index f29f833..16ed102 100644
--- a/Source/core/page/PageSerializer.cpp
+++ b/Source/core/page/PageSerializer.cpp
@@ -48,13 +48,13 @@
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLStyleElement.h"
 #include "core/html/parser/HTMLMetaCharsetParser.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/SerializedResource.h"
 #include "core/platform/graphics/Image.h"
 #include "core/rendering/RenderImage.h"
-#include "core/rendering/style/StyleCachedImage.h"
+#include "core/rendering/style/StyleFetchedImage.h"
 #include "core/rendering/style/StyleImage.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
@@ -223,13 +223,13 @@
         if (element->hasTagName(HTMLNames::imgTag)) {
             HTMLImageElement* imageElement = toHTMLImageElement(element);
             KURL url = document->completeURL(imageElement->getAttribute(HTMLNames::srcAttr));
-            CachedImage* cachedImage = imageElement->cachedImage();
+            ImageResource* cachedImage = imageElement->cachedImage();
             addImageToResources(cachedImage, imageElement->renderer(), url);
         } else if (element->hasTagName(HTMLNames::inputTag)) {
             HTMLInputElement* inputElement = toHTMLInputElement(element);
             if (inputElement->isImageButton() && inputElement->hasImageLoader()) {
                 KURL url = inputElement->src();
-                CachedImage* cachedImage = inputElement->imageLoader()->image();
+                ImageResource* cachedImage = inputElement->imageLoader()->image();
                 addImageToResources(cachedImage, inputElement->renderer(), url);
             }
         } else if (element->hasTagName(HTMLNames::linkTag)) {
@@ -288,7 +288,7 @@
     }
 }
 
-void PageSerializer::addImageToResources(CachedImage* image, RenderObject* imageRenderer, const KURL& url)
+void PageSerializer::addImageToResources(ImageResource* image, RenderObject* imageRenderer, const KURL& url)
 {
     if (!url.isValid() || m_resourceURLs.contains(url) || url.protocolIsData())
         return;
@@ -329,13 +329,13 @@
         if (!cssValue->isImageValue())
             continue;
 
-        CSSImageValue* imageValue = static_cast<CSSImageValue*>(cssValue.get());
+        CSSImageValue* imageValue = toCSSImageValue(cssValue.get());
         StyleImage* styleImage = imageValue->cachedOrPendingImage();
         // Non cached-images are just place-holders and do not contain data.
-        if (!styleImage || !styleImage->isCachedImage())
+        if (!styleImage || !styleImage->isImageResource())
             continue;
 
-        CachedImage* image = static_cast<StyleCachedImage*>(styleImage)->cachedImage();
+        ImageResource* image = static_cast<StyleFetchedImage*>(styleImage)->cachedImage();
         addImageToResources(image, 0, image->url());
     }
 }
diff --git a/Source/core/page/PageSerializer.h b/Source/core/page/PageSerializer.h
index 5913c84..296cba6 100644
--- a/Source/core/page/PageSerializer.h
+++ b/Source/core/page/PageSerializer.h
@@ -39,7 +39,7 @@
 
 namespace WebCore {
 
-class CachedImage;
+class ImageResource;
 class CSSStyleSheet;
 class Document;
 class Frame;
@@ -70,7 +70,7 @@
     // It also adds any resources included in that stylesheet (including any imported stylesheets and their own resources).
     void serializeCSSStyleSheet(CSSStyleSheet*, const KURL&);
 
-    void addImageToResources(CachedImage*, RenderObject*, const KURL&);
+    void addImageToResources(ImageResource*, RenderObject*, const KURL&);
     void retrieveResourcesForProperties(const StylePropertySet*, Document*);
     void retrieveResourcesForRule(StyleRule*, Document*);
 
diff --git a/Source/core/page/PageVisibilityState.cpp b/Source/core/page/PageVisibilityState.cpp
index 78d4c2c..630b0db 100644
--- a/Source/core/page/PageVisibilityState.cpp
+++ b/Source/core/page/PageVisibilityState.cpp
@@ -35,10 +35,10 @@
 
 String pageVisibilityStateString(PageVisibilityState state)
 {
-    DEFINE_STATIC_LOCAL(const String, visible, (ASCIILiteral("visible")));
-    DEFINE_STATIC_LOCAL(const String, hidden, (ASCIILiteral("hidden")));
-    DEFINE_STATIC_LOCAL(const String, prerender, (ASCIILiteral("prerender")));
-    DEFINE_STATIC_LOCAL(const String, preview, (ASCIILiteral("preview")));
+    DEFINE_STATIC_LOCAL(const String, visible, ("visible"));
+    DEFINE_STATIC_LOCAL(const String, hidden, ("hidden"));
+    DEFINE_STATIC_LOCAL(const String, prerender, ("prerender"));
+    DEFINE_STATIC_LOCAL(const String, preview, ("preview"));
 
     switch (state) {
     case PageVisibilityStateVisible:
diff --git a/Source/core/page/Performance.idl b/Source/core/page/Performance.idl
index e676085..8dd3ea8 100644
--- a/Source/core/page/Performance.idl
+++ b/Source/core/page/Performance.idl
@@ -30,7 +30,7 @@
  */
 
 // See: http://dev.w3.org/2006/webapi/WebTiming/
-interface Performance {
+interface Performance : EventTarget {
     readonly attribute PerformanceNavigation navigation;
     readonly attribute PerformanceTiming timing;
     readonly attribute MemoryInfo memory;
@@ -45,7 +45,7 @@
     void webkitClearResourceTimings();
     void webkitSetResourceTimingBufferSize(unsigned long maxSize);
 
-    attribute EventListener onwebkitresourcetimingbufferfull;
+    attribute EventHandler onwebkitresourcetimingbufferfull;
 
     // See http://www.w3.org/TR/2012/CR-user-timing-20120726/
     [RaisesException,MeasureAs=UnprefixedUserTiming] void mark(DOMString markName);
diff --git a/Source/core/page/PerformanceUserTiming.cpp b/Source/core/page/PerformanceUserTiming.cpp
index 70b6a57..a365c6a 100644
--- a/Source/core/page/PerformanceUserTiming.cpp
+++ b/Source/core/page/PerformanceUserTiming.cpp
@@ -101,7 +101,7 @@
 void UserTiming::mark(const String& markName, ExceptionState& es)
 {
     if (restrictedKeyMap().contains(markName)) {
-        es.throwDOMException(SyntaxError);
+        es.throwDOMException(SyntaxError, "'" + markName + "' is part of the PerformanceTiming interface, and cannot be used as a mark name.");
         return;
     }
 
@@ -122,13 +122,13 @@
     if (restrictedKeyMap().contains(markName)) {
         double value = static_cast<double>((m_performance->timing()->*(restrictedKeyMap().get(markName)))());
         if (!value) {
-            es.throwDOMException(InvalidAccessError);
+            es.throwDOMException(InvalidAccessError, "'" + markName + "' is empty: either the event hasn't happened yet, or it would provide cross-origin timing information.");
             return 0.0;
         }
         return value - m_performance->timing()->navigationStart();
     }
 
-    es.throwDOMException(SyntaxError);
+    es.throwDOMException(SyntaxError, "The mark '" + markName + "' does not exist.");
     return 0.0;
 }
 
diff --git a/Source/core/page/RuntimeEnabledFeatures.in b/Source/core/page/RuntimeEnabledFeatures.in
index d5abc7b..85faaec 100644
--- a/Source/core/page/RuntimeEnabledFeatures.in
+++ b/Source/core/page/RuntimeEnabledFeatures.in
@@ -1,4 +1,4 @@
-// http://dev.chromium.org/blink/runtime-enabled-features 
+// http://dev.chromium.org/blink/runtime-enabled-features
 //
 // This list is used to generate RuntimeEnabledFeatures.h/cpp which contains
 // a class that stores static enablers for all experimental features.
@@ -67,6 +67,7 @@
 ProgrammaticScrollNotifications status=test
 Promise status=experimental
 Quota status=stable
+OverlayScrollbars
 RequestAutocomplete status=test
 RowSpanLogicalHeightSpreading status=test
 ScriptedSpeech status=stable
@@ -79,6 +80,7 @@
 Stream status=experimental
 StyleScoped status=experimental
 Touch status=stable
+UserSelectAll status=experimental
 Vibration status=experimental
 VideoTrack status=stable
 WebAnimations
diff --git a/Source/core/page/Selection.idl b/Source/core/page/Selection.idl
index df2e24b..e5d7a9e 100644
--- a/Source/core/page/Selection.idl
+++ b/Source/core/page/Selection.idl
@@ -45,7 +45,7 @@
     [RaisesException] void collapseToEnd();
     [RaisesException] void collapseToStart();
 
-    void deleteFromDocument();
+    [CustomElementCallbacks=Enable] void deleteFromDocument();
     boolean containsNode([Default=Undefined] optional Node node,
                          [Default=Undefined] optional boolean allowPartial);
     [RaisesException] void selectAllChildren([Default=Undefined] optional Node node);
diff --git a/Source/core/page/UseCounter.cpp b/Source/core/page/UseCounter.cpp
index e941dee..7737be9 100644
--- a/Source/core/page/UseCounter.cpp
+++ b/Source/core/page/UseCounter.cpp
@@ -651,6 +651,9 @@
     case ReleaseEvents:
         return "releaseEvents() is deprecated. This method doesn't do anything.";
 
+    case ConsoleMarkTimeline:
+        return "console.markTimeline is deprecated. Please use the console.timeStamp instead.";
+
     // Features that aren't deprecated don't have a deprecation message.
     default:
         return String();
diff --git a/Source/core/page/UseCounter.h b/Source/core/page/UseCounter.h
index f0a61c5..7b5373d 100644
--- a/Source/core/page/UseCounter.h
+++ b/Source/core/page/UseCounter.h
@@ -160,6 +160,8 @@
         SubFrameBeforeUnloadFired,
         CSSPseudoElementPrefixedDistributed,
         TextReplaceWholeText,
+        PrefixedShadowRootConstructor,
+        ConsoleMarkTimeline,
         // Add new features immediately above this line. Don't change assigned
         // numbers of each items, and don't reuse unused slots.
         NumberOfFeatures, // This enum value must be last.
diff --git a/Source/core/page/UserContentURLPattern.cpp b/Source/core/page/UserContentURLPattern.cpp
index 1ebf43f..18fb2a7 100644
--- a/Source/core/page/UserContentURLPattern.cpp
+++ b/Source/core/page/UserContentURLPattern.cpp
@@ -64,7 +64,7 @@
 
 bool UserContentURLPattern::parse(const String& pattern)
 {
-    DEFINE_STATIC_LOCAL(const String, schemeSeparator, (ASCIILiteral("://")));
+    DEFINE_STATIC_LOCAL(const String, schemeSeparator, ("://"));
 
     size_t schemeEndPos = pattern.find(schemeSeparator);
     if (schemeEndPos == notFound)
diff --git a/Source/core/page/Window.idl b/Source/core/page/Window.idl
index 4434513..cbfa00a 100644
--- a/Source/core/page/Window.idl
+++ b/Source/core/page/Window.idl
@@ -169,94 +169,94 @@
     [Replaceable] readonly attribute CSS CSS;
 
     // Events
-    attribute EventListener onabort;
-    attribute EventListener onbeforeunload;
-    attribute EventListener onblur;
-    attribute EventListener oncanplay;
-    attribute EventListener oncanplaythrough;
-    attribute EventListener onchange;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onclick;
-    attribute EventListener oncontextmenu;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondblclick;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrag;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragend;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragenter;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragleave;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragover;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondragstart;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener ondrop;
-    attribute EventListener ondurationchange;
-    attribute EventListener onemptied;
-    attribute EventListener onended;
-    attribute EventListener onerror;
-    attribute EventListener onfocus;
-    attribute EventListener onhashchange;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener oninput;
-    attribute EventListener oninvalid;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeydown;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeypress;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onkeyup;
-    attribute EventListener onload;
-    attribute EventListener onloadeddata;
-    attribute EventListener onloadedmetadata;
-    attribute EventListener onloadstart;
-    attribute EventListener onmessage;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousedown;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseenter;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseleave;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousemove;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseout;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseover;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmouseup;
-    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventListener onmousewheel;
-    attribute EventListener onoffline;
-    attribute EventListener ononline;
-    attribute EventListener onpagehide;
-    attribute EventListener onpageshow;
-    attribute EventListener onpause;
-    attribute EventListener onplay;
-    attribute EventListener onplaying;
-    attribute EventListener onpopstate;
-    attribute EventListener onprogress;
-    attribute EventListener onratechange;
-    attribute EventListener onresize;
-    attribute EventListener onscroll;
-    attribute EventListener onseeked;
-    attribute EventListener onseeking;
-    attribute EventListener onselect;
-    attribute EventListener onstalled;
-    attribute EventListener onstorage;
-    attribute EventListener onsubmit;
-    attribute EventListener onsuspend;
-    attribute EventListener ontimeupdate;
-    attribute EventListener onunload;
-    attribute EventListener onvolumechange;
-    attribute EventListener onwaiting;
+    attribute EventHandler onabort;
+    attribute EventHandler onbeforeunload;
+    attribute EventHandler onblur;
+    attribute EventHandler oncanplay;
+    attribute EventHandler oncanplaythrough;
+    attribute EventHandler onchange;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onclick;
+    attribute EventHandler oncontextmenu;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondblclick;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrag;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragend;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragenter;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragleave;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragover;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragstart;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrop;
+    attribute EventHandler ondurationchange;
+    attribute EventHandler onemptied;
+    attribute EventHandler onended;
+    attribute EventHandler onerror;
+    attribute EventHandler onfocus;
+    attribute EventHandler onhashchange;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler oninput;
+    attribute EventHandler oninvalid;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeydown;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeypress;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeyup;
+    attribute EventHandler onload;
+    attribute EventHandler onloadeddata;
+    attribute EventHandler onloadedmetadata;
+    attribute EventHandler onloadstart;
+    attribute EventHandler onmessage;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousedown;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseenter;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseleave;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousemove;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
+    [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel;
+    attribute EventHandler onoffline;
+    attribute EventHandler ononline;
+    attribute EventHandler onpagehide;
+    attribute EventHandler onpageshow;
+    attribute EventHandler onpause;
+    attribute EventHandler onplay;
+    attribute EventHandler onplaying;
+    attribute EventHandler onpopstate;
+    attribute EventHandler onprogress;
+    attribute EventHandler onratechange;
+    attribute EventHandler onresize;
+    attribute EventHandler onscroll;
+    attribute EventHandler onseeked;
+    attribute EventHandler onseeking;
+    attribute EventHandler onselect;
+    attribute EventHandler onstalled;
+    attribute EventHandler onstorage;
+    attribute EventHandler onsubmit;
+    attribute EventHandler onsuspend;
+    attribute EventHandler ontimeupdate;
+    attribute EventHandler onunload;
+    attribute EventHandler onvolumechange;
+    attribute EventHandler onwaiting;
 
     // Not implemented yet.
-    // attribute EventListener onafterprint;
-    // attribute EventListener onbeforeprint;
-    // attribute EventListener onreadystatechange;
-    // attribute EventListener onredo;
-    // attribute EventListener onshow;
-    // attribute EventListener onundo;
+    // attribute EventHandler onafterprint;
+    // attribute EventHandler onbeforeprint;
+    // attribute EventHandler onreadystatechange;
+    // attribute EventHandler onredo;
+    // attribute EventHandler onshow;
+    // attribute EventHandler onundo;
 
     // Webkit extensions
-    attribute EventListener onreset;
-    attribute EventListener onsearch;
-    attribute EventListener onwebkitanimationend;
-    attribute EventListener onwebkitanimationiteration;
-    attribute EventListener onwebkitanimationstart;
-    attribute EventListener onwebkittransitionend;
-    attribute EventListener ontransitionend;
-    [Conditional=ORIENTATION_EVENTS] attribute EventListener onorientationchange;
-    [EnabledAtRuntime=touch] attribute EventListener ontouchstart;
-    [EnabledAtRuntime=touch] attribute EventListener ontouchmove;
-    [EnabledAtRuntime=touch] attribute EventListener ontouchend;
-    [EnabledAtRuntime=touch] attribute EventListener ontouchcancel;
+    attribute EventHandler onreset;
+    attribute EventHandler onsearch;
+    attribute EventHandler onwebkitanimationend;
+    attribute EventHandler onwebkitanimationiteration;
+    attribute EventHandler onwebkitanimationstart;
+    attribute EventHandler onwebkittransitionend;
+    attribute EventHandler ontransitionend;
+    [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
+    [EnabledAtRuntime=touch] attribute EventHandler ontouchstart;
+    [EnabledAtRuntime=touch] attribute EventHandler ontouchmove;
+    [EnabledAtRuntime=touch] attribute EventHandler ontouchend;
+    [EnabledAtRuntime=touch] attribute EventHandler ontouchcancel;
 
-    [EnabledAtRuntime=deviceMotion] attribute EventListener ondevicemotion;
-    [EnabledAtRuntime=deviceOrientation] attribute EventListener ondeviceorientation;
+    [EnabledAtRuntime=deviceMotion] attribute EventHandler ondevicemotion;
+    [EnabledAtRuntime=deviceOrientation] attribute EventHandler ondeviceorientation;
 
     [DeprecateAs=CaptureEvents] void captureEvents();
     [DeprecateAs=ReleaseEvents] void releaseEvents();
@@ -296,7 +296,7 @@
     // FIXME: When it's ready to remove WebKitShadowRoot, get rid of both constructors from Window.idl and remove
     // [NoInterfaceObject] from ShadowRoot interface definition.
     [EnabledAtRuntime=ShadowDOM] attribute ShadowRootConstructor ShadowRoot;
-    attribute ShadowRootConstructor WebKitShadowRoot;
+    [MeasureAs=PrefixedShadowRootConstructor] attribute ShadowRootConstructor WebKitShadowRoot;
 
     // window.toString() requires special handling in V8
     [DoNotCheckSignature, DoNotCheckSecurity, Custom, NotEnumerable] DOMString toString();
diff --git a/Source/core/page/animation/CSSPropertyAnimation.cpp b/Source/core/page/animation/CSSPropertyAnimation.cpp
index 2a1b103..5bf3bb6 100644
--- a/Source/core/page/animation/CSSPropertyAnimation.cpp
+++ b/Source/core/page/animation/CSSPropertyAnimation.cpp
@@ -36,13 +36,13 @@
 #include "core/css/CSSCrossfadeValue.h"
 #include "core/css/CSSImageValue.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/animation/AnimationBase.h"
 #include "core/platform/FloatConversion.h"
 #include "core/rendering/ClipPathOperation.h"
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/StyleCachedImage.h"
+#include "core/rendering/style/StyleFetchedImage.h"
 #include "core/rendering/style/StyleGeneratedImage.h"
 #include "wtf/Noncopyable.h"
 
@@ -123,7 +123,7 @@
 {
     if (anim->isTransformFunctionListValid())
         return to.blendByMatchingOperations(from, progress);
-    return to.blendByUsingMatrixInterpolation(from, progress, anim->renderer()->isBox() ? toRenderBox(anim->renderer())->borderBoxRect().size() : LayoutSize());
+    return to.blendByUsingMatrixInterpolation(from, progress);
 }
 
 static inline PassRefPtr<ClipPathOperation> blendFunc(const AnimationBase*, ClipPathOperation* from, ClipPathOperation* to, double progress)
@@ -159,10 +159,6 @@
 static inline PassRefPtr<FilterOperation> blendFunc(const AnimationBase* anim, FilterOperation* fromOp, FilterOperation* toOp, double progress, bool blendToPassthrough = false)
 {
     ASSERT(toOp);
-    if (toOp->blendingNeedsRendererSize()) {
-        LayoutSize size = anim->renderer()->isBox() ? toRenderBox(anim->renderer())->borderBoxRect().size() : LayoutSize();
-        return toOp->blend(fromOp, progress, size, blendToPassthrough);
-    }
     return toOp->blend(fromOp, progress, blendToPassthrough);
 }
 
@@ -231,7 +227,31 @@
     return to.blend(from, narrowPrecisionToFloat(progress));
 }
 
-static inline PassRefPtr<StyleImage> crossfadeBlend(const AnimationBase*, StyleCachedImage* fromStyleImage, StyleCachedImage* toStyleImage, double progress)
+static inline Vector<SVGLength> blendFunc(const AnimationBase*, const Vector<SVGLength>& from, const Vector<SVGLength>& to, double progress)
+{
+    size_t fromLength = from.size();
+    size_t toLength = to.size();
+    if (!fromLength)
+        return !progress ? from : to;
+    if (!toLength)
+        return progress == 1 ? from : to;
+
+    size_t resultLength = fromLength;
+    if (fromLength != toLength) {
+        if (!(fromLength % toLength))
+            resultLength = fromLength;
+        else if (!(toLength % fromLength))
+            resultLength = toLength;
+        else
+            resultLength = fromLength * toLength;
+    }
+    Vector<SVGLength> result(resultLength);
+    for (size_t i = 0; i < resultLength; ++i)
+        result[i] = to[i % toLength].blend(from[i % fromLength], narrowPrecisionToFloat(progress));
+    return result;
+}
+
+static inline PassRefPtr<StyleImage> crossfadeBlend(const AnimationBase*, StyleFetchedImage* fromStyleImage, StyleFetchedImage* toStyleImage, double progress)
 {
     // If progress is at one of the extremes, we want getComputedStyle to show the image,
     // not a completed cross-fade, so we hand back one of the existing images.
@@ -240,11 +260,11 @@
     if (progress == 1)
         return toStyleImage;
 
-    CachedImage* fromCachedImage = static_cast<CachedImage*>(fromStyleImage->data());
-    CachedImage* toCachedImage = static_cast<CachedImage*>(toStyleImage->data());
+    ImageResource* fromImageResource = static_cast<ImageResource*>(fromStyleImage->data());
+    ImageResource* toImageResource = static_cast<ImageResource*>(toStyleImage->data());
 
-    RefPtr<CSSImageValue> fromImageValue = CSSImageValue::create(fromCachedImage->url(), fromStyleImage);
-    RefPtr<CSSImageValue> toImageValue = CSSImageValue::create(toCachedImage->url(), toStyleImage);
+    RefPtr<CSSImageValue> fromImageValue = CSSImageValue::create(fromImageResource->url(), fromStyleImage);
+    RefPtr<CSSImageValue> toImageValue = CSSImageValue::create(toImageResource->url(), toStyleImage);
     RefPtr<CSSCrossfadeValue> crossfadeValue = CSSCrossfadeValue::create(fromImageValue, toImageValue);
 
     crossfadeValue->setPercentage(CSSPrimitiveValue::create(progress, CSSPrimitiveValue::CSS_NUMBER));
@@ -257,8 +277,8 @@
     if (!from || !to)
         return to;
 
-    if (from->isCachedImage() && to->isCachedImage())
-        return crossfadeBlend(anim, static_cast<StyleCachedImage*>(from), static_cast<StyleCachedImage*>(to), progress);
+    if (from->isImageResource() && to->isImageResource())
+        return crossfadeBlend(anim, static_cast<StyleFetchedImage*>(from), static_cast<StyleFetchedImage*>(to), progress);
 
     // FIXME: Support transitioning generated images as well. (gradients, etc.)
 
@@ -1159,6 +1179,7 @@
     gPropertyWrappers->append(new PropertyWrapperSVGPaint(CSSPropertyStroke, &RenderStyle::strokePaintType, &RenderStyle::strokePaintColor, &RenderStyle::setStrokePaintColor));
     gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeOpacity, &RenderStyle::strokeOpacity, &RenderStyle::setStrokeOpacity));
     gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyStrokeWidth, &RenderStyle::strokeWidth, &RenderStyle::setStrokeWidth));
+    gPropertyWrappers->append(new PropertyWrapper< Vector<SVGLength> >(CSSPropertyStrokeDasharray, &RenderStyle::strokeDashArray, &RenderStyle::setStrokeDashArray));
     gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyStrokeDashoffset, &RenderStyle::strokeDashOffset, &RenderStyle::setStrokeDashOffset));
     gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeMiterlimit, &RenderStyle::strokeMiterLimit, &RenderStyle::setStrokeMiterLimit));
 
diff --git a/Source/core/page/animation/CompositeAnimation.cpp b/Source/core/page/animation/CompositeAnimation.cpp
index 057023b..7615715 100644
--- a/Source/core/page/animation/CompositeAnimation.cpp
+++ b/Source/core/page/animation/CompositeAnimation.cpp
@@ -61,7 +61,6 @@
         }
     }
     if (!m_keyframeAnimations.isEmpty()) {
-        m_keyframeAnimations.checkConsistency();
         AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
         for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
             KeyframeAnimation* anim = it->value.get();
@@ -194,8 +193,6 @@
     if (m_keyframeAnimations.isEmpty() && !targetStyle->hasAnimations())
         return;
 
-    m_keyframeAnimations.checkConsistency();
-
     AnimationNameMap::const_iterator kfend = m_keyframeAnimations.end();
 
     if (currentStyle && currentStyle->hasAnimations() && targetStyle->hasAnimations() && *(currentStyle->animations()) == *(targetStyle->animations())) {
@@ -286,7 +283,6 @@
     // We don't do any transitions if we don't have a currentStyle (on startup).
     updateTransitions(renderer, currentStyle, targetStyle);
     updateKeyframeAnimations(renderer, currentStyle, targetStyle);
-    m_keyframeAnimations.checkConsistency();
 
     if (currentStyle) {
         // Now that we have transition objects ready, let them know about the new goal state.  We want them
@@ -320,8 +316,6 @@
             implicitAnimation->getAnimatedStyle(resultStyle);
     }
 
-    m_keyframeAnimations.checkConsistency();
-
     for (Vector<AtomicString>::const_iterator it = m_keyframeAnimationOrderList.begin(); it != m_keyframeAnimationOrderList.end(); ++it) {
         RefPtr<KeyframeAnimation> keyframeAnimation = m_keyframeAnimations.get(*it);
         ASSERT(keyframeAnimation);
@@ -349,7 +343,6 @@
         }
     }
     if (!m_keyframeAnimations.isEmpty()) {
-        m_keyframeAnimations.checkConsistency();
         AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
         for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
             KeyframeAnimation* animation = it->value.get();
@@ -385,7 +378,6 @@
         }
     }
     if (!m_keyframeAnimations.isEmpty()) {
-        m_keyframeAnimations.checkConsistency();
         AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
         for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
             KeyframeAnimation* animation = it->value.get();
@@ -410,7 +402,6 @@
     // We want to send back the last animation with the property if there are multiples.
     // So we need to iterate through all animations
     if (!m_keyframeAnimations.isEmpty()) {
-        m_keyframeAnimations.checkConsistency();
         AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
         for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
             RefPtr<KeyframeAnimation> anim = it->value;
@@ -430,7 +421,6 @@
     m_suspended = true;
 
     if (!m_keyframeAnimations.isEmpty()) {
-        m_keyframeAnimations.checkConsistency();
         AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
         for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
             if (KeyframeAnimation* anim = it->value.get())
@@ -455,7 +445,6 @@
     m_suspended = false;
 
     if (!m_keyframeAnimations.isEmpty()) {
-        m_keyframeAnimations.checkConsistency();
         AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
         for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
             KeyframeAnimation* anim = it->value.get();
@@ -501,7 +490,6 @@
 bool CompositeAnimation::isAnimatingProperty(CSSPropertyID property, bool acceleratedOnly, bool isRunningNow) const
 {
     if (!m_keyframeAnimations.isEmpty()) {
-        m_keyframeAnimations.checkConsistency();
         AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
         for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
             KeyframeAnimation* anim = it->value.get();
@@ -523,8 +511,6 @@
 
 void CompositeAnimation::pauseAnimationsForTesting(double t)
 {
-    m_keyframeAnimations.checkConsistency();
-
     AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
     for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
         RefPtr<KeyframeAnimation> keyframeAnim = it->value;
@@ -553,7 +539,6 @@
     unsigned count = 0;
 
     if (!m_keyframeAnimations.isEmpty()) {
-        m_keyframeAnimations.checkConsistency();
         AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
         for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
             KeyframeAnimation* anim = it->value.get();
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.cpp b/Source/core/page/scrolling/ScrollingCoordinator.cpp
index 6d24bf2..30975d1 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -36,7 +36,7 @@
 #include "core/page/Page.h"
 #include "core/platform/PlatformWheelEvent.h"
 #include "core/platform/ScrollAnimator.h"
-#include "core/platform/ScrollbarThemeComposite.h"
+#include "core/platform/ScrollbarTheme.h"
 #include "core/platform/chromium/TraceEvent.h"
 #include "core/platform/chromium/support/WebScrollbarImpl.h"
 #include "core/platform/chromium/support/WebScrollbarThemeGeometryNative.h"
@@ -198,10 +198,9 @@
 
 static PassOwnPtr<WebScrollbarLayer> createScrollbarLayer(Scrollbar* scrollbar)
 {
-    // All Chromium scrollbar themes derive from ScrollbarThemeComposite.
-    ScrollbarThemeComposite* themeComposite = static_cast<ScrollbarThemeComposite*>(scrollbar->theme());
-    WebKit::WebScrollbarThemePainter painter(themeComposite, scrollbar);
-    OwnPtr<WebKit::WebScrollbarThemeGeometry> geometry(WebKit::WebScrollbarThemeGeometryNative::create(themeComposite));
+    ScrollbarTheme* theme = scrollbar->theme();
+    WebKit::WebScrollbarThemePainter painter(theme, scrollbar);
+    OwnPtr<WebKit::WebScrollbarThemeGeometry> geometry(WebKit::WebScrollbarThemeGeometryNative::create(theme));
 
     OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createScrollbarLayer(new WebKit::WebScrollbarImpl(scrollbar), painter, geometry.leakPtr()));
     GraphicsLayer::registerContentsLayer(scrollbarLayer->layer());
@@ -342,7 +341,6 @@
         LayerHitTestRects::iterator compIter = compositorRects.find(compositedLayer);
         if (compIter == compositorRects.end())
             compIter = compositorRects.add(compositedLayer, Vector<LayoutRect>()).iterator;
-
         // Transform each rect to the co-ordinate space of it's enclosing composited layer.
         // Ideally we'd compute a transformation matrix once and re-use it for each rect.
         // RenderGeometryMap can be used for this (but needs to be updated to support crossing
@@ -359,6 +357,8 @@
     }
 }
 
+// Note that in principle this could be called more often than computeTouchEventTargetRects, for
+// example during a non-composited scroll (although that's not yet implemented - crbug.com/261307).
 void ScrollingCoordinator::setTouchEventTargetRects(const LayerHitTestRects& layerRects)
 {
     TRACE_EVENT0("input", "ScrollingCoordinator::setTouchEventTargetRects");
@@ -446,7 +446,6 @@
 
 Region ScrollingCoordinator::computeShouldHandleScrollGestureOnMainThreadRegion(const Frame* frame, const IntPoint& frameLocation) const
 {
-    TRACE_EVENT0("input", "ScrollingCoordinator::computeShouldHandleScrollGestureOnMainThreadRegion");
     Region shouldHandleScrollGestureOnMainThreadRegion;
     FrameView* frameView = frame->view();
     if (!frameView)
@@ -540,7 +539,15 @@
             ASSERT(target != document);
             accumulateDocumentTouchEventTargetRects(rects, toDocument(target));
         } else if (RenderObject* renderer = target->renderer()) {
-            renderer->computeLayerHitTestRects(rects);
+            // If the set also contains one of our ancestor nodes then processing
+            // this node would be redundant.
+            bool hasTouchEventTargetAncestor = false;
+            for (Node* ancestor = target->parentNode(); ancestor && !hasTouchEventTargetAncestor; ancestor = ancestor->parentNode()) {
+                if (targets->contains(ancestor))
+                    hasTouchEventTargetAncestor = true;
+            }
+            if (!hasTouchEventTargetAncestor)
+                renderer->computeLayerHitTestRects(rects);
         }
     }
 
diff --git a/Source/core/platform/CrossThreadCopier.h b/Source/core/platform/CrossThreadCopier.h
index e0ebbc6..8e8220b 100644
--- a/Source/core/platform/CrossThreadCopier.h
+++ b/Source/core/platform/CrossThreadCopier.h
@@ -36,7 +36,7 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
-#include "wtf/Threading.h"
+#include "wtf/ThreadSafeRefCounted.h"
 #include "wtf/TypeTraits.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/DragData.cpp b/Source/core/platform/DragData.cpp
index e68643c..90e4605 100644
--- a/Source/core/platform/DragData.cpp
+++ b/Source/core/platform/DragData.cpp
@@ -44,7 +44,7 @@
 
 namespace WebCore {
 
-DragData::DragData(DragDataRef data, const IntPoint& clientPosition, const IntPoint& globalPosition,
+DragData::DragData(ChromiumDataObject* data, const IntPoint& clientPosition, const IntPoint& globalPosition,
     DragOperation sourceOperationMask, DragApplicationFlags flags)
     : m_clientPosition(clientPosition)
     , m_globalPosition(globalPosition)
diff --git a/Source/core/platform/DragData.h b/Source/core/platform/DragData.h
index a9a23aa..cf8fad1 100644
--- a/Source/core/platform/DragData.h
+++ b/Source/core/platform/DragData.h
@@ -27,7 +27,6 @@
 #define DragData_h
 
 #include "core/page/DragActions.h"
-#include "core/platform/chromium/DragDataRef.h"
 #include "core/platform/graphics/IntPoint.h"
 
 #include "wtf/Forward.h"
@@ -36,8 +35,9 @@
 
 namespace WebCore {
 
-class Frame;
+class ChromiumDataObject;
 class DocumentFragment;
+class Frame;
 class KURL;
 class Range;
 
@@ -54,12 +54,12 @@
     enum FilenameConversionPolicy { DoNotConvertFilenames, ConvertFilenames };
 
     // clientPosition is taken to be the position of the drag event within the target window, with (0,0) at the top left
-    DragData(DragDataRef, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
+    DragData(ChromiumDataObject*, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
     DragData(const String& dragStorageName, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
     const IntPoint& clientPosition() const { return m_clientPosition; }
     const IntPoint& globalPosition() const { return m_globalPosition; }
     DragApplicationFlags flags() const { return m_applicationFlags; }
-    DragDataRef platformData() const { return m_platformDragData; }
+    ChromiumDataObject* platformData() const { return m_platformDragData; }
     DragOperation draggingSourceOperationMask() const { return m_draggingSourceOperationMask; }
     bool containsURL(Frame*, FilenameConversionPolicy filenamePolicy = ConvertFilenames) const;
     bool containsPlainText() const;
@@ -79,7 +79,7 @@
 private:
     IntPoint m_clientPosition;
     IntPoint m_globalPosition;
-    DragDataRef m_platformDragData;
+    ChromiumDataObject* m_platformDragData;
     DragOperation m_draggingSourceOperationMask;
     DragApplicationFlags m_applicationFlags;
 };
diff --git a/Source/core/platform/MIMETypeRegistry.h b/Source/core/platform/MIMETypeRegistry.h
index 9062e26..983aa85 100644
--- a/Source/core/platform/MIMETypeRegistry.h
+++ b/Source/core/platform/MIMETypeRegistry.h
@@ -38,8 +38,6 @@
     static String getMIMETypeForExtension(const String& extension);
     static String getWellKnownMIMETypeForExtension(const String& extension);
 
-    static String getPreferredExtensionForMIMEType(const String& type);
-
     static String getMIMETypeForPath(const String& path);
 
     // Check to see if a mime type is suitable for being loaded inline as an
diff --git a/Source/core/platform/ScrollbarTheme.cpp b/Source/core/platform/ScrollbarTheme.cpp
index a65d3ed..2835183 100644
--- a/Source/core/platform/ScrollbarTheme.cpp
+++ b/Source/core/platform/ScrollbarTheme.cpp
@@ -27,6 +27,8 @@
 #include "core/platform/ScrollbarTheme.h"
 
 #include "core/page/Settings.h"
+#include "core/platform/ScrollbarThemeClient.h"
+#include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/mock/ScrollbarThemeMock.h"
 
 namespace WebCore {
@@ -40,4 +42,264 @@
     return nativeTheme();
 }
 
+bool ScrollbarTheme::paint(ScrollbarThemeClient* scrollbar, GraphicsContext* graphicsContext, const IntRect& damageRect)
+{
+    // Create the ScrollbarControlPartMask based on the damageRect
+    ScrollbarControlPartMask scrollMask = NoPart;
+
+    IntRect backButtonStartPaintRect;
+    IntRect backButtonEndPaintRect;
+    IntRect forwardButtonStartPaintRect;
+    IntRect forwardButtonEndPaintRect;
+    if (hasButtons(scrollbar)) {
+        backButtonStartPaintRect = backButtonRect(scrollbar, BackButtonStartPart, true);
+        if (damageRect.intersects(backButtonStartPaintRect))
+            scrollMask |= BackButtonStartPart;
+        backButtonEndPaintRect = backButtonRect(scrollbar, BackButtonEndPart, true);
+        if (damageRect.intersects(backButtonEndPaintRect))
+            scrollMask |= BackButtonEndPart;
+        forwardButtonStartPaintRect = forwardButtonRect(scrollbar, ForwardButtonStartPart, true);
+        if (damageRect.intersects(forwardButtonStartPaintRect))
+            scrollMask |= ForwardButtonStartPart;
+        forwardButtonEndPaintRect = forwardButtonRect(scrollbar, ForwardButtonEndPart, true);
+        if (damageRect.intersects(forwardButtonEndPaintRect))
+            scrollMask |= ForwardButtonEndPart;
+    }
+
+    IntRect startTrackRect;
+    IntRect thumbRect;
+    IntRect endTrackRect;
+    IntRect trackPaintRect = trackRect(scrollbar, true);
+    if (damageRect.intersects(trackPaintRect))
+        scrollMask |= TrackBGPart;
+    bool thumbPresent = hasThumb(scrollbar);
+    if (thumbPresent) {
+        IntRect track = trackRect(scrollbar);
+        splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect);
+        if (damageRect.intersects(thumbRect))
+            scrollMask |= ThumbPart;
+        if (damageRect.intersects(startTrackRect))
+            scrollMask |= BackTrackPart;
+        if (damageRect.intersects(endTrackRect))
+            scrollMask |= ForwardTrackPart;
+    }
+
+    // Paint the scrollbar background (only used by custom CSS scrollbars).
+    paintScrollbarBackground(graphicsContext, scrollbar);
+
+    // Paint the back and forward buttons.
+    if (scrollMask & BackButtonStartPart)
+        paintButton(graphicsContext, scrollbar, backButtonStartPaintRect, BackButtonStartPart);
+    if (scrollMask & BackButtonEndPart)
+        paintButton(graphicsContext, scrollbar, backButtonEndPaintRect, BackButtonEndPart);
+    if (scrollMask & ForwardButtonStartPart)
+        paintButton(graphicsContext, scrollbar, forwardButtonStartPaintRect, ForwardButtonStartPart);
+    if (scrollMask & ForwardButtonEndPart)
+        paintButton(graphicsContext, scrollbar, forwardButtonEndPaintRect, ForwardButtonEndPart);
+
+    if (scrollMask & TrackBGPart)
+        paintTrackBackground(graphicsContext, scrollbar, trackPaintRect);
+
+    if ((scrollMask & ForwardTrackPart) || (scrollMask & BackTrackPart)) {
+        // Paint the track pieces above and below the thumb.
+        if (scrollMask & BackTrackPart)
+            paintTrackPiece(graphicsContext, scrollbar, startTrackRect, BackTrackPart);
+        if (scrollMask & ForwardTrackPart)
+            paintTrackPiece(graphicsContext, scrollbar, endTrackRect, ForwardTrackPart);
+
+        paintTickmarks(graphicsContext, scrollbar, trackPaintRect);
+    }
+
+    // Paint the thumb.
+    if (scrollMask & ThumbPart)
+        paintThumb(graphicsContext, scrollbar, thumbRect);
+
+    return true;
+}
+
+ScrollbarPart ScrollbarTheme::hitTest(ScrollbarThemeClient* scrollbar, const IntPoint& position)
+{
+    ScrollbarPart result = NoPart;
+    if (!scrollbar->enabled())
+        return result;
+
+    IntPoint testPosition = scrollbar->convertFromContainingWindow(position);
+    testPosition.move(scrollbar->x(), scrollbar->y());
+
+    if (!scrollbar->frameRect().contains(testPosition))
+        return NoPart;
+
+    result = ScrollbarBGPart;
+
+    IntRect track = trackRect(scrollbar);
+    if (track.contains(testPosition)) {
+        IntRect beforeThumbRect;
+        IntRect thumbRect;
+        IntRect afterThumbRect;
+        splitTrack(scrollbar, track, beforeThumbRect, thumbRect, afterThumbRect);
+        if (thumbRect.contains(testPosition))
+            result = ThumbPart;
+        else if (beforeThumbRect.contains(testPosition))
+            result = BackTrackPart;
+        else if (afterThumbRect.contains(testPosition))
+            result = ForwardTrackPart;
+        else
+            result = TrackBGPart;
+    } else if (backButtonRect(scrollbar, BackButtonStartPart).contains(testPosition)) {
+        result = BackButtonStartPart;
+    } else if (backButtonRect(scrollbar, BackButtonEndPart).contains(testPosition)) {
+        result = BackButtonEndPart;
+    } else if (forwardButtonRect(scrollbar, ForwardButtonStartPart).contains(testPosition)) {
+        result = ForwardButtonStartPart;
+    } else if (forwardButtonRect(scrollbar, ForwardButtonEndPart).contains(testPosition)) {
+        result = ForwardButtonEndPart;
+    }
+    return result;
+}
+
+void ScrollbarTheme::invalidatePart(ScrollbarThemeClient* scrollbar, ScrollbarPart part)
+{
+    if (part == NoPart)
+        return;
+
+    IntRect result;
+    switch (part) {
+    case BackButtonStartPart:
+        result = backButtonRect(scrollbar, BackButtonStartPart, true);
+        break;
+    case BackButtonEndPart:
+        result = backButtonRect(scrollbar, BackButtonEndPart, true);
+        break;
+    case ForwardButtonStartPart:
+        result = forwardButtonRect(scrollbar, ForwardButtonStartPart, true);
+        break;
+    case ForwardButtonEndPart:
+        result = forwardButtonRect(scrollbar, ForwardButtonEndPart, true);
+        break;
+    case TrackBGPart:
+        result = trackRect(scrollbar, true);
+        break;
+    case ScrollbarBGPart:
+        result = scrollbar->frameRect();
+        break;
+    default: {
+        IntRect beforeThumbRect, thumbRect, afterThumbRect;
+        splitTrack(scrollbar, trackRect(scrollbar), beforeThumbRect, thumbRect, afterThumbRect);
+        if (part == BackTrackPart)
+            result = beforeThumbRect;
+        else if (part == ForwardTrackPart)
+            result = afterThumbRect;
+        else
+            result = thumbRect;
+    }
+    }
+    result.moveBy(-scrollbar->location());
+    scrollbar->invalidateRect(result);
+}
+
+void ScrollbarTheme::splitTrack(ScrollbarThemeClient* scrollbar, const IntRect& unconstrainedTrackRect, IntRect& beforeThumbRect, IntRect& thumbRect, IntRect& afterThumbRect)
+{
+    // This function won't even get called unless we're big enough to have some combination of these three rects where at least
+    // one of them is non-empty.
+    IntRect trackRect = constrainTrackRectToTrackPieces(scrollbar, unconstrainedTrackRect);
+    int thickness = scrollbar->orientation() == HorizontalScrollbar ? scrollbar->height() : scrollbar->width();
+    int thumbPos = thumbPosition(scrollbar);
+    if (scrollbar->orientation() == HorizontalScrollbar) {
+        thumbRect = IntRect(trackRect.x() + thumbPos, trackRect.y() + (trackRect.height() - thickness) / 2, thumbLength(scrollbar), thickness);
+        beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), thumbPos + thumbRect.width() / 2, trackRect.height());
+        afterThumbRect = IntRect(trackRect.x() + beforeThumbRect.width(), trackRect.y(), trackRect.maxX() - beforeThumbRect.maxX(), trackRect.height());
+    } else {
+        thumbRect = IntRect(trackRect.x() + (trackRect.width() - thickness) / 2, trackRect.y() + thumbPos, thickness, thumbLength(scrollbar));
+        beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), trackRect.width(), thumbPos + thumbRect.height() / 2);
+        afterThumbRect = IntRect(trackRect.x(), trackRect.y() + beforeThumbRect.height(), trackRect.width(), trackRect.maxY() - beforeThumbRect.maxY());
+    }
+}
+
+// Returns the size represented by track taking into account scrolling past
+// the end of the document.
+static float usedTotalSize(ScrollbarThemeClient* scrollbar)
+{
+    float overhangAtStart = -scrollbar->currentPos();
+    float overhangAtEnd = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize();
+    float overhang = std::max(0.0f, std::max(overhangAtStart, overhangAtEnd));
+    return scrollbar->totalSize() + overhang;
+}
+
+int ScrollbarTheme::thumbPosition(ScrollbarThemeClient* scrollbar)
+{
+    if (scrollbar->enabled()) {
+        float size = usedTotalSize(scrollbar) - scrollbar->visibleSize();
+        // Avoid doing a floating point divide by zero and return 1 when usedTotalSize == visibleSize.
+        if (!size)
+            return 1;
+        float pos = std::max(0.0f, scrollbar->currentPos()) * (trackLength(scrollbar) - thumbLength(scrollbar)) / size;
+        return (pos < 1 && pos > 0) ? 1 : pos;
+    }
+    return 0;
+}
+
+int ScrollbarTheme::thumbLength(ScrollbarThemeClient* scrollbar)
+{
+    if (!scrollbar->enabled())
+        return 0;
+
+    float overhang = 0;
+    if (scrollbar->currentPos() < 0)
+        overhang = -scrollbar->currentPos();
+    else if (scrollbar->visibleSize() + scrollbar->currentPos() > scrollbar->totalSize())
+        overhang = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize();
+    float proportion = (scrollbar->visibleSize() - overhang) / usedTotalSize(scrollbar);
+    int trackLen = trackLength(scrollbar);
+    int length = round(proportion * trackLen);
+    length = std::max(length, minimumThumbLength(scrollbar));
+    if (length > trackLen)
+        length = 0; // Once the thumb is below the track length, it just goes away (to make more room for the track).
+    return length;
+}
+
+int ScrollbarTheme::minimumThumbLength(ScrollbarThemeClient* scrollbar)
+{
+    return scrollbarThickness(scrollbar->controlSize());
+}
+
+int ScrollbarTheme::trackPosition(ScrollbarThemeClient* scrollbar)
+{
+    IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar));
+    return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.x() - scrollbar->x() : constrainedTrackRect.y() - scrollbar->y();
+}
+
+int ScrollbarTheme::trackLength(ScrollbarThemeClient* scrollbar)
+{
+    IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar));
+    return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.width() : constrainedTrackRect.height();
+}
+
+void ScrollbarTheme::paintScrollCorner(ScrollView*, GraphicsContext* context, const IntRect& cornerRect)
+{
+    context->fillRect(cornerRect, Color::white);
+}
+
+IntRect ScrollbarTheme::thumbRect(ScrollbarThemeClient* scrollbar)
+{
+    if (!hasThumb(scrollbar))
+        return IntRect();
+
+    IntRect track = trackRect(scrollbar);
+    IntRect startTrackRect;
+    IntRect thumbRect;
+    IntRect endTrackRect;
+    splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect);
+
+    return thumbRect;
+}
+
+void ScrollbarTheme::paintOverhangAreas(ScrollView*, GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect& dirtyRect)
+{
+    context->setFillColor(Color::white);
+    if (!horizontalOverhangRect.isEmpty())
+        context->fillRect(intersection(horizontalOverhangRect, dirtyRect));
+    if (!verticalOverhangRect.isEmpty())
+        context->fillRect(intersection(verticalOverhangRect, dirtyRect));
+}
+
 }
diff --git a/Source/core/platform/ScrollbarTheme.h b/Source/core/platform/ScrollbarTheme.h
index 2015bf1..fdfd727 100644
--- a/Source/core/platform/ScrollbarTheme.h
+++ b/Source/core/platform/ScrollbarTheme.h
@@ -44,12 +44,12 @@
     WTF_MAKE_NONCOPYABLE(ScrollbarTheme); WTF_MAKE_FAST_ALLOCATED;
 public:
     ScrollbarTheme() { }
-    virtual ~ScrollbarTheme() {};
+    virtual ~ScrollbarTheme() { }
 
-    virtual void updateEnabledState(ScrollbarThemeClient*) { };
+    virtual void updateEnabledState(ScrollbarThemeClient*) { }
 
-    virtual bool paint(ScrollbarThemeClient*, GraphicsContext*, const IntRect& /*damageRect*/) { return false; }
-    virtual ScrollbarPart hitTest(ScrollbarThemeClient*, const IntPoint&) { return NoPart; }
+    virtual bool paint(ScrollbarThemeClient*, GraphicsContext*, const IntRect& damageRect);
+    virtual ScrollbarPart hitTest(ScrollbarThemeClient*, const IntPoint&);
 
     virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) { return 0; }
 
@@ -59,7 +59,7 @@
     virtual bool usesOverlayScrollbars() const { return false; }
     virtual void updateScrollbarOverlayStyle(ScrollbarThemeClient*) { }
 
-    virtual void themeChanged() {}
+    virtual void themeChanged() { }
 
     virtual bool invalidateOnMouseEnterExit() { return false; }
 
@@ -81,27 +81,51 @@
             invalidatePart(scrollbar, ForwardButtonEndPart);
     }
 
-    virtual void invalidatePart(ScrollbarThemeClient*, ScrollbarPart) { }
+    virtual void invalidatePart(ScrollbarThemeClient*, ScrollbarPart);
 
-    virtual void paintScrollCorner(ScrollView*, GraphicsContext* context, const IntRect& cornerRect) { defaultPaintScrollCorner(context, cornerRect); }
-    static void defaultPaintScrollCorner(GraphicsContext* context, const IntRect& cornerRect) { context->fillRect(cornerRect, Color::white); }
+    virtual void paintScrollCorner(ScrollView*, GraphicsContext*, const IntRect& cornerRect);
 
     virtual void paintTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) { }
-    virtual void paintOverhangAreas(ScrollView*, GraphicsContext*, const IntRect&, const IntRect&, const IntRect&) { }
+    virtual void paintOverhangAreas(ScrollView*, GraphicsContext*, const IntRect&, const IntRect&, const IntRect&);
 
     virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) { return false; }
     virtual bool shouldSnapBackToDragOrigin(ScrollbarThemeClient*, const PlatformMouseEvent&) { return false; }
     virtual bool shouldDragDocumentInsteadOfThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) { return false; }
-    virtual int thumbPosition(ScrollbarThemeClient*) { return 0; } // The position of the thumb relative to the track.
-    virtual int thumbLength(ScrollbarThemeClient*) { return 0; } // The length of the thumb along the axis of the scrollbar.
-    virtual int trackPosition(ScrollbarThemeClient*) { return 0; } // The position of the track relative to the scrollbar.
-    virtual int trackLength(ScrollbarThemeClient*) { return 0; } // The length of the track along the axis of the scrollbar.
+
+    // The position of the thumb relative to the track.
+    virtual int thumbPosition(ScrollbarThemeClient*);
+    // The length of the thumb along the axis of the scrollbar.
+    virtual int thumbLength(ScrollbarThemeClient*);
+    // The position of the track relative to the scrollbar.
+    virtual int trackPosition(ScrollbarThemeClient*);
+    // The length of the track along the axis of the scrollbar.
+    virtual int trackLength(ScrollbarThemeClient*);
+
+    virtual bool hasButtons(ScrollbarThemeClient*) = 0;
+    virtual bool hasThumb(ScrollbarThemeClient*) = 0;
+
+    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) = 0;
+    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) = 0;
+    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) = 0;
+    virtual IntRect thumbRect(ScrollbarThemeClient*);
+
+    virtual int minimumThumbLength(ScrollbarThemeClient*);
+
+    virtual void splitTrack(ScrollbarThemeClient*, const IntRect& track, IntRect& startTrack, IntRect& thumb, IntRect& endTrack);
+
+    virtual void paintScrollbarBackground(GraphicsContext*, ScrollbarThemeClient*) { }
+    virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) { }
+    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) { }
+    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) { }
+    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) { }
 
     virtual int maxOverlapBetweenPages() { return std::numeric_limits<int>::max(); }
 
     virtual double initialAutoscrollTimerDelay() { return 0.25; }
     virtual double autoscrollTimerDelay() { return 0.05; }
 
+    virtual IntRect constrainTrackRectToTrackPieces(ScrollbarThemeClient*, const IntRect& rect) { return rect; }
+
     virtual void registerScrollbar(ScrollbarThemeClient*) { }
     virtual void unregisterScrollbar(ScrollbarThemeClient*) { }
 
diff --git a/Source/core/platform/ScrollbarThemeComposite.cpp b/Source/core/platform/ScrollbarThemeComposite.cpp
deleted file mode 100644
index ec628ee..0000000
--- a/Source/core/platform/ScrollbarThemeComposite.cpp
+++ /dev/null
@@ -1,295 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarThemeComposite.h"
-
-#include "core/platform/ScrollbarThemeClient.h"
-#include "core/platform/graphics/GraphicsContext.h"
-
-using namespace std;
-
-namespace WebCore {
-
-bool ScrollbarThemeComposite::paint(ScrollbarThemeClient* scrollbar, GraphicsContext* graphicsContext, const IntRect& damageRect)
-{
-    // Create the ScrollbarControlPartMask based on the damageRect
-    ScrollbarControlPartMask scrollMask = NoPart;
-
-    IntRect backButtonStartPaintRect;
-    IntRect backButtonEndPaintRect;
-    IntRect forwardButtonStartPaintRect;
-    IntRect forwardButtonEndPaintRect;
-    if (hasButtons(scrollbar)) {
-        backButtonStartPaintRect = backButtonRect(scrollbar, BackButtonStartPart, true);
-        if (damageRect.intersects(backButtonStartPaintRect))
-            scrollMask |= BackButtonStartPart;
-        backButtonEndPaintRect = backButtonRect(scrollbar, BackButtonEndPart, true);
-        if (damageRect.intersects(backButtonEndPaintRect))
-            scrollMask |= BackButtonEndPart;
-        forwardButtonStartPaintRect = forwardButtonRect(scrollbar, ForwardButtonStartPart, true);
-        if (damageRect.intersects(forwardButtonStartPaintRect))
-            scrollMask |= ForwardButtonStartPart;
-        forwardButtonEndPaintRect = forwardButtonRect(scrollbar, ForwardButtonEndPart, true);
-        if (damageRect.intersects(forwardButtonEndPaintRect))
-            scrollMask |= ForwardButtonEndPart;
-    }
-
-    IntRect startTrackRect;
-    IntRect thumbRect;
-    IntRect endTrackRect;
-    IntRect trackPaintRect = trackRect(scrollbar, true);
-    if (damageRect.intersects(trackPaintRect))
-        scrollMask |= TrackBGPart;
-    bool thumbPresent = hasThumb(scrollbar);
-    if (thumbPresent) {
-        IntRect track = trackRect(scrollbar);
-        splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect);
-        if (damageRect.intersects(thumbRect))
-            scrollMask |= ThumbPart;
-        if (damageRect.intersects(startTrackRect))
-            scrollMask |= BackTrackPart;
-        if (damageRect.intersects(endTrackRect))
-            scrollMask |= ForwardTrackPart;
-    }
-
-    // Paint the scrollbar background (only used by custom CSS scrollbars).
-    paintScrollbarBackground(graphicsContext, scrollbar);
-
-    // Paint the back and forward buttons.
-    if (scrollMask & BackButtonStartPart)
-        paintButton(graphicsContext, scrollbar, backButtonStartPaintRect, BackButtonStartPart);
-    if (scrollMask & BackButtonEndPart)
-        paintButton(graphicsContext, scrollbar, backButtonEndPaintRect, BackButtonEndPart);
-    if (scrollMask & ForwardButtonStartPart)
-        paintButton(graphicsContext, scrollbar, forwardButtonStartPaintRect, ForwardButtonStartPart);
-    if (scrollMask & ForwardButtonEndPart)
-        paintButton(graphicsContext, scrollbar, forwardButtonEndPaintRect, ForwardButtonEndPart);
-
-    if (scrollMask & TrackBGPart)
-        paintTrackBackground(graphicsContext, scrollbar, trackPaintRect);
-
-    if ((scrollMask & ForwardTrackPart) || (scrollMask & BackTrackPart)) {
-        // Paint the track pieces above and below the thumb.
-        if (scrollMask & BackTrackPart)
-            paintTrackPiece(graphicsContext, scrollbar, startTrackRect, BackTrackPart);
-        if (scrollMask & ForwardTrackPart)
-            paintTrackPiece(graphicsContext, scrollbar, endTrackRect, ForwardTrackPart);
-
-        paintTickmarks(graphicsContext, scrollbar, trackPaintRect);
-    }
-
-    // Paint the thumb.
-    if (scrollMask & ThumbPart)
-        paintThumb(graphicsContext, scrollbar, thumbRect);
-
-    return true;
-}
-
-ScrollbarPart ScrollbarThemeComposite::hitTest(ScrollbarThemeClient* scrollbar, const IntPoint& position)
-{
-    ScrollbarPart result = NoPart;
-    if (!scrollbar->enabled())
-        return result;
-
-    IntPoint testPosition = scrollbar->convertFromContainingWindow(position);
-    testPosition.move(scrollbar->x(), scrollbar->y());
-
-    if (!scrollbar->frameRect().contains(testPosition))
-        return NoPart;
-
-    result = ScrollbarBGPart;
-
-    IntRect track = trackRect(scrollbar);
-    if (track.contains(testPosition)) {
-        IntRect beforeThumbRect;
-        IntRect thumbRect;
-        IntRect afterThumbRect;
-        splitTrack(scrollbar, track, beforeThumbRect, thumbRect, afterThumbRect);
-        if (thumbRect.contains(testPosition))
-            result = ThumbPart;
-        else if (beforeThumbRect.contains(testPosition))
-            result = BackTrackPart;
-        else if (afterThumbRect.contains(testPosition))
-            result = ForwardTrackPart;
-        else
-            result = TrackBGPart;
-    } else if (backButtonRect(scrollbar, BackButtonStartPart).contains(testPosition))
-        result = BackButtonStartPart;
-    else if (backButtonRect(scrollbar, BackButtonEndPart).contains(testPosition))
-        result = BackButtonEndPart;
-    else if (forwardButtonRect(scrollbar, ForwardButtonStartPart).contains(testPosition))
-        result = ForwardButtonStartPart;
-    else if (forwardButtonRect(scrollbar, ForwardButtonEndPart).contains(testPosition))
-        result = ForwardButtonEndPart;
-    return result;
-}
-
-void ScrollbarThemeComposite::invalidatePart(ScrollbarThemeClient* scrollbar, ScrollbarPart part)
-{
-    if (part == NoPart)
-        return;
-
-    IntRect result;
-    switch (part) {
-        case BackButtonStartPart:
-            result = backButtonRect(scrollbar, BackButtonStartPart, true);
-            break;
-        case BackButtonEndPart:
-            result = backButtonRect(scrollbar, BackButtonEndPart, true);
-            break;
-        case ForwardButtonStartPart:
-            result = forwardButtonRect(scrollbar, ForwardButtonStartPart, true);
-            break;
-        case ForwardButtonEndPart:
-            result = forwardButtonRect(scrollbar, ForwardButtonEndPart, true);
-            break;
-        case TrackBGPart:
-            result = trackRect(scrollbar, true);
-            break;
-        case ScrollbarBGPart:
-            result = scrollbar->frameRect();
-            break;
-        default: {
-            IntRect beforeThumbRect, thumbRect, afterThumbRect;
-            splitTrack(scrollbar, trackRect(scrollbar), beforeThumbRect, thumbRect, afterThumbRect);
-            if (part == BackTrackPart)
-                result = beforeThumbRect;
-            else if (part == ForwardTrackPart)
-                result = afterThumbRect;
-            else
-                result = thumbRect;
-        }
-    }
-    result.moveBy(-scrollbar->location());
-    scrollbar->invalidateRect(result);
-}
-
-void ScrollbarThemeComposite::splitTrack(ScrollbarThemeClient* scrollbar, const IntRect& unconstrainedTrackRect, IntRect& beforeThumbRect, IntRect& thumbRect, IntRect& afterThumbRect)
-{
-    // This function won't even get called unless we're big enough to have some combination of these three rects where at least
-    // one of them is non-empty.
-    IntRect trackRect = constrainTrackRectToTrackPieces(scrollbar, unconstrainedTrackRect);
-    int thickness = scrollbar->orientation() == HorizontalScrollbar ? scrollbar->height() : scrollbar->width();
-    int thumbPos = thumbPosition(scrollbar);
-    if (scrollbar->orientation() == HorizontalScrollbar) {
-        thumbRect = IntRect(trackRect.x() + thumbPos, trackRect.y() + (trackRect.height() - thickness) / 2, thumbLength(scrollbar), thickness);
-        beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), thumbPos + thumbRect.width() / 2, trackRect.height());
-        afterThumbRect = IntRect(trackRect.x() + beforeThumbRect.width(), trackRect.y(), trackRect.maxX() - beforeThumbRect.maxX(), trackRect.height());
-    } else {
-        thumbRect = IntRect(trackRect.x() + (trackRect.width() - thickness) / 2, trackRect.y() + thumbPos, thickness, thumbLength(scrollbar));
-        beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), trackRect.width(), thumbPos + thumbRect.height() / 2);
-        afterThumbRect = IntRect(trackRect.x(), trackRect.y() + beforeThumbRect.height(), trackRect.width(), trackRect.maxY() - beforeThumbRect.maxY());
-    }
-}
-
-// Returns the size represented by track taking into account scrolling past
-// the end of the document.
-static float usedTotalSize(ScrollbarThemeClient* scrollbar)
-{
-    float overhangAtStart = -scrollbar->currentPos();
-    float overhangAtEnd = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize();
-    float overhang = max(0.0f, max(overhangAtStart, overhangAtEnd));
-    return scrollbar->totalSize() + overhang;
-}
-
-int ScrollbarThemeComposite::thumbPosition(ScrollbarThemeClient* scrollbar)
-{
-    if (scrollbar->enabled()) {
-        float size = usedTotalSize(scrollbar) - scrollbar->visibleSize();
-        // Avoid doing a floating point divide by zero and return 1 when usedTotalSize == visibleSize.
-        if (!size)
-            return 1;
-        float pos = max(0.0f, scrollbar->currentPos()) * (trackLength(scrollbar) - thumbLength(scrollbar)) / size;
-        return (pos < 1 && pos > 0) ? 1 : pos;
-    }
-    return 0;
-}
-
-int ScrollbarThemeComposite::thumbLength(ScrollbarThemeClient* scrollbar)
-{
-    if (!scrollbar->enabled())
-        return 0;
-
-    float overhang = 0;
-    if (scrollbar->currentPos() < 0)
-        overhang = -scrollbar->currentPos();
-    else if (scrollbar->visibleSize() + scrollbar->currentPos() > scrollbar->totalSize())
-        overhang = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize();
-    float proportion = (scrollbar->visibleSize() - overhang) / usedTotalSize(scrollbar);
-    int trackLen = trackLength(scrollbar);
-    int length = round(proportion * trackLen);
-    length = max(length, minimumThumbLength(scrollbar));
-    if (length > trackLen)
-        length = 0; // Once the thumb is below the track length, it just goes away (to make more room for the track).
-    return length;
-}
-
-int ScrollbarThemeComposite::minimumThumbLength(ScrollbarThemeClient* scrollbar)
-{
-    return scrollbarThickness(scrollbar->controlSize());
-}
-
-int ScrollbarThemeComposite::trackPosition(ScrollbarThemeClient* scrollbar)
-{
-    IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar));
-    return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.x() - scrollbar->x() : constrainedTrackRect.y() - scrollbar->y();
-}
-
-int ScrollbarThemeComposite::trackLength(ScrollbarThemeClient* scrollbar)
-{
-    IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar));
-    return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.width() : constrainedTrackRect.height();
-}
-
-void ScrollbarThemeComposite::paintScrollCorner(ScrollView*, GraphicsContext* context, const IntRect& cornerRect)
-{
-    context->fillRect(cornerRect, Color::white);
-}
-
-IntRect ScrollbarThemeComposite::thumbRect(ScrollbarThemeClient* scrollbar)
-{
-    if (!hasThumb(scrollbar))
-        return IntRect();
-
-    IntRect track = trackRect(scrollbar);
-    IntRect startTrackRect;
-    IntRect thumbRect;
-    IntRect endTrackRect;
-    splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect);
-
-    return thumbRect;
-}
-
-void ScrollbarThemeComposite::paintOverhangAreas(ScrollView*, GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect& dirtyRect)
-{
-    context->setFillColor(Color::white);
-    if (!horizontalOverhangRect.isEmpty())
-        context->fillRect(intersection(horizontalOverhangRect, dirtyRect));
-    if (!verticalOverhangRect.isEmpty())
-        context->fillRect(intersection(verticalOverhangRect, dirtyRect));
-}
-
-}
diff --git a/Source/core/platform/ScrollbarThemeComposite.h b/Source/core/platform/ScrollbarThemeComposite.h
deleted file mode 100644
index 7b6cc0c..0000000
--- a/Source/core/platform/ScrollbarThemeComposite.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeComposite_h
-#define ScrollbarThemeComposite_h
-
-#include "core/platform/ScrollbarTheme.h"
-
-namespace WebCore {
-
-class ScrollbarThemeComposite : public ScrollbarTheme {
-public:
-    // Implement ScrollbarTheme interface
-    virtual bool paint(ScrollbarThemeClient*, GraphicsContext*, const IntRect& damageRect);
-    virtual ScrollbarPart hitTest(ScrollbarThemeClient*, const IntPoint&);
-    virtual void invalidatePart(ScrollbarThemeClient*, ScrollbarPart);
-    virtual int thumbPosition(ScrollbarThemeClient*);
-    virtual int thumbLength(ScrollbarThemeClient*);
-    virtual int trackPosition(ScrollbarThemeClient*);
-    virtual int trackLength(ScrollbarThemeClient*);
-    virtual void paintScrollCorner(ScrollView*, GraphicsContext*, const IntRect& cornerRect);
-    virtual void paintOverhangAreas(ScrollView*, GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect);
-
-    virtual bool hasButtons(ScrollbarThemeClient*) = 0;
-    virtual bool hasThumb(ScrollbarThemeClient*) = 0;
-
-    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) = 0;
-    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) = 0;
-    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) = 0;
-    virtual IntRect thumbRect(ScrollbarThemeClient*);
-
-    virtual void splitTrack(ScrollbarThemeClient*, const IntRect& track, IntRect& startTrack, IntRect& thumb, IntRect& endTrack);
-
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
-
-    virtual void paintScrollbarBackground(GraphicsContext*, ScrollbarThemeClient*) { }
-    virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) { }
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) { }
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) { }
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) { }
-
-    virtual IntRect constrainTrackRectToTrackPieces(ScrollbarThemeClient*, const IntRect& rect) { return rect; }
-};
-
-}
-#endif
diff --git a/Source/core/platform/SharedBuffer.cpp b/Source/core/platform/SharedBuffer.cpp
index b33d623..ce2c37a 100644
--- a/Source/core/platform/SharedBuffer.cpp
+++ b/Source/core/platform/SharedBuffer.cpp
@@ -235,6 +235,36 @@
     return this->buffer().data();
 }
 
+void SharedBuffer::moveTo(Vector<char>& result)
+{
+    ASSERT(result.isEmpty());
+    if (m_purgeableBuffer) {
+        result.reserveCapacity(m_purgeableBuffer->size());
+        result.append(m_purgeableBuffer->data(), m_purgeableBuffer->size());
+        clear();
+        return;
+    }
+
+    unsigned bufferSize = m_buffer.size();
+    if (m_size == bufferSize) {
+        m_buffer.swap(result);
+        clear();
+        return;
+    }
+
+    result.reserveCapacity(m_size);
+
+    const char* segment = 0;
+    unsigned position = 0;
+    while (unsigned segmentSize = getSomeData(segment, position)) {
+        result.append(segment, segmentSize);
+        position += segmentSize;
+    }
+    ASSERT(result.size() == m_size);
+    clear();
+    return;
+}
+
 void SharedBuffer::append(SharedBuffer* data)
 {
     const char* segment;
diff --git a/Source/core/platform/SharedBuffer.h b/Source/core/platform/SharedBuffer.h
index b5b1fa6..4e6dcf8 100644
--- a/Source/core/platform/SharedBuffer.h
+++ b/Source/core/platform/SharedBuffer.h
@@ -58,6 +58,8 @@
     // for better performance.
     const char* data() const;
 
+    void moveTo(Vector<char>&);
+
     unsigned size() const;
 
     bool isEmpty() const { return !size(); }
diff --git a/Source/core/platform/SharedBufferTest.cpp b/Source/core/platform/SharedBufferTest.cpp
index ed4963e..1afa914 100644
--- a/Source/core/platform/SharedBufferTest.cpp
+++ b/Source/core/platform/SharedBufferTest.cpp
@@ -58,6 +58,48 @@
     EXPECT_EQ(0, memcmp(expectedConcatenation, arrayBuffer->data(), strlen(expectedConcatenation)));
 }
 
+TEST(SharedBufferTest, moveToAvoidsMemcpy)
+{
+    char testData[] = "Hello";
+
+    RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(testData, strlen(testData));
+
+    const char* originalData = sharedBuffer->data();
+    const size_t originalSize = sharedBuffer->size();
+
+    Vector<char> result;
+    sharedBuffer->moveTo(result);
+
+    EXPECT_TRUE(sharedBuffer->isEmpty());
+    EXPECT_EQ(originalData, result.data());
+    EXPECT_EQ(originalSize, result.size());
+}
+
+TEST(SharedBufferTest, moveToHandlesSegments)
+{
+    Vector<char> vector0(0x4000);
+    for (size_t i = 0; i < vector0.size(); ++i)
+        vector0[i] = 'a';
+    Vector<char> vector1(0x4000);
+    for (size_t i = 0; i < vector1.size(); ++i)
+        vector1[i] = 'b';
+    Vector<char> vector2(0x4000);
+    for (size_t i = 0; i < vector2.size(); ++i)
+        vector2[i] = 'c';
+
+    RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::adoptVector(vector0);
+    sharedBuffer->append(vector1);
+    sharedBuffer->append(vector2);
+
+    const size_t originalSize = sharedBuffer->size();
+
+    Vector<char> result;
+    sharedBuffer->moveTo(result);
+
+    EXPECT_TRUE(sharedBuffer->isEmpty());
+    EXPECT_EQ(originalSize, result.size());
+}
+
 TEST(SharedBufferTest, getAsArrayBufferLargeSegments)
 {
     Vector<char> vector0(0x4000);
diff --git a/Source/core/platform/Widget.h b/Source/core/platform/Widget.h
index 0454440..6a871a3 100644
--- a/Source/core/platform/Widget.h
+++ b/Source/core/platform/Widget.h
@@ -130,6 +130,9 @@
     // A means to access the AX cache when this object can get a pointer to it.
     virtual AXObjectCache* axObjectCache() const { return 0; }
 
+    // Notifies this widget that it will no longer be receiving events.
+    virtual void eventListenersRemoved() { }
+
 private:
     ScrollView* m_parent;
     IntRect m_frame;
diff --git a/Source/core/platform/animation/CSSAnimationData.cpp b/Source/core/platform/animation/CSSAnimationData.cpp
index a1957bb..65f2fa6 100644
--- a/Source/core/platform/animation/CSSAnimationData.cpp
+++ b/Source/core/platform/animation/CSSAnimationData.cpp
@@ -136,7 +136,7 @@
 
 const String& CSSAnimationData::initialAnimationName()
 {
-    DEFINE_STATIC_LOCAL(String, initialValue, (ASCIILiteral("none")));
+    DEFINE_STATIC_LOCAL(String, initialValue, ("none"));
     return initialValue;
 }
 
diff --git a/Source/core/platform/chromium/ClipboardChromium.cpp b/Source/core/platform/chromium/ClipboardChromium.cpp
index 188cc6f..50e69e5 100644
--- a/Source/core/platform/chromium/ClipboardChromium.cpp
+++ b/Source/core/platform/chromium/ClipboardChromium.cpp
@@ -34,11 +34,10 @@
 #include "core/dom/Element.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/StringCallback.h"
-#include "core/editing/Editor.h"
 #include "core/editing/markup.h"
 #include "core/fileapi/File.h"
 #include "core/fileapi/FileList.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/platform/DragData.h"
 #include "core/platform/MIMETypeRegistry.h"
@@ -299,7 +298,7 @@
     return files.release();
 }
 
-void ClipboardChromium::setDragImage(CachedImage* image, Node* node, const IntPoint& loc)
+void ClipboardChromium::setDragImage(ImageResource* image, Node* node, const IntPoint& loc)
 {
     if (!canSetDragImage())
         return;
@@ -314,7 +313,7 @@
     m_dragImageElement = node;
 }
 
-void ClipboardChromium::setDragImage(CachedImage* img, const IntPoint& loc)
+void ClipboardChromium::setDragImage(ImageResource* img, const IntPoint& loc)
 {
     setDragImage(img, 0, loc);
 }
@@ -338,9 +337,9 @@
     return nullptr;
 }
 
-static CachedImage* getCachedImage(Element* element)
+static ImageResource* getImageResource(Element* element)
 {
-    // Attempt to pull CachedImage from element
+    // Attempt to pull ImageResource from element
     ASSERT(element);
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isImage())
@@ -357,7 +356,7 @@
                                    const KURL& url)
 {
     // Shove image data into a DataObject for use as a file
-    CachedImage* cachedImage = getCachedImage(element);
+    ImageResource* cachedImage = getImageResource(element);
     if (!cachedImage || !cachedImage->imageForRenderer(element->renderer()) || !cachedImage->isLoaded())
         return;
 
@@ -436,7 +435,7 @@
 
     m_dataObject->setHTMLAndBaseURL(createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs), frame->document()->url());
 
-    String str = frame->editor()->selectedTextForClipboard();
+    String str = frame->selectedTextForClipboard();
 #if OS(WINDOWS)
     replaceNewlinesWithWindowsStyleNewlines(str);
 #endif
diff --git a/Source/core/platform/chromium/ClipboardChromium.h b/Source/core/platform/chromium/ClipboardChromium.h
index 9df2d14..980a22d 100644
--- a/Source/core/platform/chromium/ClipboardChromium.h
+++ b/Source/core/platform/chromium/ClipboardChromium.h
@@ -32,12 +32,12 @@
 
 #include "core/dom/Clipboard.h"
 #include "core/dom/DataTransferItem.h"
-#include "core/loader/cache/CachedImageClient.h"
+#include "core/loader/cache/ImageResourceClient.h"
 #include "core/platform/chromium/ChromiumDataObject.h"
 
 namespace WebCore {
 
-    class CachedImage;
+class ImageResource;
     class ChromiumDataObjectItem;
     class ClipboardChromium;
     class Frame;
@@ -64,7 +64,7 @@
         RefPtr<ChromiumDataObjectItem> m_item;
     };
 
-    class ClipboardChromium : public Clipboard, public CachedImageClient {
+    class ClipboardChromium : public Clipboard, public ImageResourceClient {
         WTF_MAKE_FAST_ALLOCATED;
     public:
         ~ClipboardChromium();
@@ -87,7 +87,7 @@
         virtual ListHashSet<String> types() const;
         virtual PassRefPtr<FileList> files() const;
 
-        void setDragImage(CachedImage*, const IntPoint&);
+        void setDragImage(ImageResource*, const IntPoint&);
         void setDragImageElement(Node*, const IntPoint&);
 
         PassRefPtr<ChromiumDataObject> dataObject()
@@ -110,7 +110,7 @@
         ClipboardChromium(ClipboardType, PassRefPtr<ChromiumDataObject>, ClipboardAccessPolicy, Frame*);
 
         void resetFromClipboard();
-        void setDragImage(CachedImage*, Node*, const IntPoint&);
+        void setDragImage(ImageResource*, Node*, const IntPoint&);
         RefPtr<ChromiumDataObject> m_dataObject;
         Frame* m_frame;
     };
diff --git a/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp b/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp
index a3f4457..cec9ed9 100644
--- a/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp
+++ b/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp
@@ -49,7 +49,7 @@
 #if OS(WINDOWS)
 void replaceNewlinesWithWindowsStyleNewlines(String& str)
 {
-    DEFINE_STATIC_LOCAL(String, windowsNewline, (ASCIILiteral("\r\n")));
+    DEFINE_STATIC_LOCAL(String, windowsNewline, ("\r\n"));
     StringBuilder result;
     for (unsigned index = 0; index < str.length(); ++index) {
         if (str[index] != '\n' || (index > 0 && str[index - 1] == '\r'))
diff --git a/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp b/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp
index 8144762..3df86e1 100644
--- a/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp
+++ b/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp
@@ -37,10 +37,6 @@
 #include "public/platform/WebMimeRegistry.h"
 #include "wtf/text/CString.h"
 
-// NOTE: Unlike other ports, we don't use the shared implementation in
-// MIMETypeRegistry.cpp.  Instead, we need to route most functions via
-// Platform.h to the embedder.
-
 namespace WebCore {
 
 String MIMETypeRegistry::getMIMETypeForExtension(const String &ext)
@@ -54,21 +50,6 @@
     return WebKit::Platform::current()->mimeRegistry()->wellKnownMimeTypeForExtension(ext);
 }
 
-// Returns the file extension if one is found.  Does not include the dot in the
-// filename.  E.g., 'html'.
-String MIMETypeRegistry::getPreferredExtensionForMIMEType(const String& type)
-{
-    // Prune out any parameters in case they happen to have snuck in there...
-    // FIXME: Is this really necessary??
-    String mimeType = type.substring(0, static_cast<unsigned>(type.find(';')));
-
-    String ext = WebKit::Platform::current()->mimeRegistry()->preferredExtensionForMIMEType(type);
-    if (!ext.isEmpty() && ext[0] == '.')
-        ext = ext.substring(1);
-
-    return ext;
-}
-
 String MIMETypeRegistry::getMIMETypeForPath(const String& path)
 {
     int pos = path.reverseFind('.');
diff --git a/Source/core/platform/chromium/PasteboardChromium.cpp b/Source/core/platform/chromium/PasteboardChromium.cpp
index fd1711f..d06f207 100644
--- a/Source/core/platform/chromium/PasteboardChromium.cpp
+++ b/Source/core/platform/chromium/PasteboardChromium.cpp
@@ -38,10 +38,9 @@
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/Element.h"
 #include "core/dom/Range.h"
-#include "core/editing/Editor.h"
 #include "core/editing/markup.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/platform/chromium/ClipboardChromium.h"
 #include "core/platform/chromium/ClipboardUtilitiesChromium.h"
@@ -86,7 +85,7 @@
 {
     String html = createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs);
     KURL url = selectedRange->startContainer()->document()->url();
-    String plainText = shouldSerializeSelectedTextForClipboard == IncludeImageAltTextForClipboard ? frame->editor()->selectedTextForClipboard() : frame->editor()->selectedText();
+    String plainText = shouldSerializeSelectedTextForClipboard == IncludeImageAltTextForClipboard ? frame->selectedTextForClipboard() : frame->selectedText();
 #if OS(WINDOWS)
     replaceNewlinesWithWindowsStyleNewlines(plainText);
 #endif
@@ -129,7 +128,7 @@
         return;
 
     RenderImage* renderer = toRenderImage(node->renderer());
-    CachedImage* cachedImage = renderer->cachedImage();
+    ImageResource* cachedImage = renderer->cachedImage();
     if (!cachedImage || cachedImage->errorOccurred())
         return;
     Image* image = cachedImage->imageForRenderer(renderer);
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromium.cpp b/Source/core/platform/chromium/ScrollbarThemeChromium.cpp
index 24be4b7..d44a778 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromium.cpp
+++ b/Source/core/platform/chromium/ScrollbarThemeChromium.cpp
@@ -30,7 +30,7 @@
 #include "core/platform/PlatformMouseEvent.h"
 #include "core/platform/ScrollableArea.h"
 #include "core/platform/Scrollbar.h"
-#include "core/platform/ScrollbarThemeComposite.h"
+#include "core/platform/ScrollbarTheme.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 
 // -----------------------------------------------------------------------------
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromium.h b/Source/core/platform/chromium/ScrollbarThemeChromium.h
index de65466..9866a17 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromium.h
+++ b/Source/core/platform/chromium/ScrollbarThemeChromium.h
@@ -31,28 +31,29 @@
 #ifndef ScrollbarThemeChromium_h
 #define ScrollbarThemeChromium_h
 
-#include "core/platform/ScrollbarThemeComposite.h"
+#include "core/platform/ScrollbarTheme.h"
 
 namespace WebCore {
 
-    class PlatformMouseEvent;
+class PlatformMouseEvent;
 
-    // This class contains the scrollbar code which is shared between Chromium
-    // Windows and Linux.
-    class ScrollbarThemeChromium : public ScrollbarThemeComposite {
-    protected:
-        virtual bool hasButtons(ScrollbarThemeClient*) { return true; }
-        virtual bool hasThumb(ScrollbarThemeClient*);
+// This class contains the scrollbar code which is shared between Chromium
+// Windows and Linux.
+class ScrollbarThemeChromium : public ScrollbarTheme {
+protected:
+    virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE { return true; }
+    virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
 
-        virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
-        virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
-        virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false);
+    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
+    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
+    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
 
-        virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-        virtual void paintTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
+    virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
+    virtual void paintTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
 
-        virtual IntSize buttonSize(ScrollbarThemeClient*) = 0;
-    };
+    virtual IntSize buttonSize(ScrollbarThemeClient*) = 0;
+};
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp b/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp
index 0be8300..ca8b507 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp
+++ b/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp
@@ -24,94 +24,17 @@
  */
 
 #include "config.h"
-#include "core/platform/chromium/ScrollbarThemeChromiumAndroid.h"
 
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
+#include "core/platform/ScrollbarTheme.h"
 
-#include <algorithm>
-
-using namespace std;
+#include "core/platform/chromium/ScrollbarThemeChromiumOverlay.h"
 
 namespace WebCore {
 
-static const int scrollbarWidth = 3;
-static const int scrollbarMargin = 4;
-
 ScrollbarTheme* ScrollbarTheme::nativeTheme()
 {
-    DEFINE_STATIC_LOCAL(ScrollbarThemeChromiumAndroid, theme, ());
+    DEFINE_STATIC_LOCAL(ScrollbarThemeChromiumOverlay, theme, ());
     return &theme;
 }
 
-int ScrollbarThemeChromiumAndroid::scrollbarThickness(ScrollbarControlSize controlSize)
-{
-    return scrollbarWidth + scrollbarMargin;
-}
-
-bool ScrollbarThemeChromiumAndroid::usesOverlayScrollbars() const
-{
-    return true;
-}
-
-int ScrollbarThemeChromiumAndroid::thumbPosition(ScrollbarThemeClient* scrollbar)
-{
-    if (!scrollbar->totalSize())
-        return 0;
-
-    int trackLen = trackLength(scrollbar);
-    float proportion = static_cast<float>(scrollbar->currentPos()) / scrollbar->totalSize();
-    return round(proportion * trackLen);
-}
-
-int ScrollbarThemeChromiumAndroid::thumbLength(ScrollbarThemeClient* scrollbar)
-{
-    int trackLen = trackLength(scrollbar);
-
-    if (!scrollbar->totalSize())
-        return trackLen;
-
-    float proportion = (float)scrollbar->visibleSize() / scrollbar->totalSize();
-    int length = round(proportion * trackLen);
-    length = min(max(length, minimumThumbLength(scrollbar)), trackLen);
-    return length;
-}
-
-bool ScrollbarThemeChromiumAndroid::hasThumb(ScrollbarThemeClient* scrollbar)
-{
-    return true;
-}
-
-IntRect ScrollbarThemeChromiumAndroid::backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
-{
-    return IntRect();
-}
-
-IntRect ScrollbarThemeChromiumAndroid::forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
-{
-    return IntRect();
-}
-
-IntRect ScrollbarThemeChromiumAndroid::trackRect(ScrollbarThemeClient* scrollbar, bool)
-{
-    IntRect rect = scrollbar->frameRect();
-    if (scrollbar->orientation() == HorizontalScrollbar)
-        rect.inflateX(-scrollbarMargin);
-    else
-        rect.inflateY(-scrollbarMargin);
-    return rect;
-}
-
-void ScrollbarThemeChromiumAndroid::paintThumb(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
-{
-    IntRect thumbRect = rect;
-    if (scrollbar->orientation() == HorizontalScrollbar)
-        thumbRect.setHeight(thumbRect.height() - scrollbarMargin);
-    else
-        thumbRect.setWidth(thumbRect.width() - scrollbarMargin);
-    context->fillRect(thumbRect, Color(128, 128, 128, 128));
-}
-
 } // namespace WebCore
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.cpp b/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.cpp
index bbb50d2..721870a 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.cpp
+++ b/Source/core/platform/chromium/ScrollbarThemeChromiumDefault.cpp
@@ -31,8 +31,10 @@
 #include "config.h"
 #include "core/platform/chromium/ScrollbarThemeChromiumDefault.h"
 
+#include "RuntimeEnabledFeatures.h"
 #include "core/platform/PlatformMouseEvent.h"
 #include "core/platform/Scrollbar.h"
+#include "core/platform/chromium/ScrollbarThemeChromiumOverlay.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "public/platform/default/WebThemeEngine.h"
 #include "public/platform/Platform.h"
@@ -42,6 +44,11 @@
 
 ScrollbarTheme* ScrollbarTheme::nativeTheme()
 {
+    if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) {
+        DEFINE_STATIC_LOCAL(ScrollbarThemeChromiumOverlay, theme, ());
+        return &theme;
+    }
+
     DEFINE_STATIC_LOCAL(ScrollbarThemeChromiumDefault, theme, ());
     return &theme;
 }
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp b/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp
new file mode 100644
index 0000000..c10c89b
--- /dev/null
+++ b/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1.  Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ * 2.  Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/platform/chromium/ScrollbarThemeChromiumOverlay.h"
+
+#include "core/platform/PlatformMouseEvent.h"
+#include "core/platform/Scrollbar.h"
+#include "core/platform/graphics/GraphicsContext.h"
+#include "core/platform/graphics/transforms/TransformationMatrix.h"
+
+#include <algorithm>
+
+using namespace std;
+
+namespace WebCore {
+
+static const int scrollbarWidth = 3;
+static const int scrollbarMargin = 4;
+
+int ScrollbarThemeChromiumOverlay::scrollbarThickness(ScrollbarControlSize controlSize)
+{
+    return scrollbarWidth + scrollbarMargin;
+}
+
+bool ScrollbarThemeChromiumOverlay::usesOverlayScrollbars() const
+{
+    return true;
+}
+
+int ScrollbarThemeChromiumOverlay::thumbPosition(ScrollbarThemeClient* scrollbar)
+{
+    if (!scrollbar->totalSize())
+        return 0;
+
+    int trackLen = trackLength(scrollbar);
+    float proportion = static_cast<float>(scrollbar->currentPos()) / scrollbar->totalSize();
+    return round(proportion * trackLen);
+}
+
+int ScrollbarThemeChromiumOverlay::thumbLength(ScrollbarThemeClient* scrollbar)
+{
+    int trackLen = trackLength(scrollbar);
+
+    if (!scrollbar->totalSize())
+        return trackLen;
+
+    float proportion = (float)scrollbar->visibleSize() / scrollbar->totalSize();
+    int length = round(proportion * trackLen);
+    length = min(max(length, minimumThumbLength(scrollbar)), trackLen);
+    return length;
+}
+
+bool ScrollbarThemeChromiumOverlay::hasThumb(ScrollbarThemeClient* scrollbar)
+{
+    return true;
+}
+
+IntRect ScrollbarThemeChromiumOverlay::backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
+{
+    return IntRect();
+}
+
+IntRect ScrollbarThemeChromiumOverlay::forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
+{
+    return IntRect();
+}
+
+IntRect ScrollbarThemeChromiumOverlay::trackRect(ScrollbarThemeClient* scrollbar, bool)
+{
+    IntRect rect = scrollbar->frameRect();
+    if (scrollbar->orientation() == HorizontalScrollbar)
+        rect.inflateX(-scrollbarMargin);
+    else
+        rect.inflateY(-scrollbarMargin);
+    return rect;
+}
+
+void ScrollbarThemeChromiumOverlay::paintThumb(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
+{
+    IntRect thumbRect = rect;
+    if (scrollbar->orientation() == HorizontalScrollbar)
+        thumbRect.setHeight(thumbRect.height() - scrollbarMargin);
+    else
+        thumbRect.setWidth(thumbRect.width() - scrollbarMargin);
+    context->fillRect(thumbRect, Color(128, 128, 128, 128));
+}
+
+} // namespace WebCore
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.h b/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.h
similarity index 66%
rename from Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.h
rename to Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.h
index 027d809..291ef8c 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.h
+++ b/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.h
@@ -23,29 +23,31 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ScrollbarThemeChromiumAndroid_h
-#define ScrollbarThemeChromiumAndroid_h
+#ifndef ScrollbarThemeChromiumOverlay_h
+#define ScrollbarThemeChromiumOverlay_h
 
-#include "core/platform/chromium/ScrollbarThemeChromium.h"
+#include "core/platform/ScrollbarTheme.h"
 
 namespace WebCore {
 
-class ScrollbarThemeChromiumAndroid : public ScrollbarThemeComposite {
+// This scrollbar theme is used to get overlay scrollbar for platforms other
+// than Mac. Mac's overlay scrollbars are in ScrollbarThemeMac*.
+class ScrollbarThemeChromiumOverlay : public ScrollbarTheme {
 public:
-    virtual int scrollbarThickness(ScrollbarControlSize);
-    virtual bool usesOverlayScrollbars() const;
+    virtual int scrollbarThickness(ScrollbarControlSize) OVERRIDE;
+    virtual bool usesOverlayScrollbars() const OVERRIDE;
 
-    virtual int thumbPosition(ScrollbarThemeClient*);
-    virtual int thumbLength(ScrollbarThemeClient*);
+    virtual int thumbPosition(ScrollbarThemeClient*) OVERRIDE;
+    virtual int thumbLength(ScrollbarThemeClient*) OVERRIDE;
 
-    virtual bool hasButtons(ScrollbarThemeClient*) { return false; };
-    virtual bool hasThumb(ScrollbarThemeClient*);
+    virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE { return false; };
+    virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
 
-    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
-    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
-    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false);
+    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
+    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
+    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
 
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
+    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/chromium/ScrollbarThemeChromiumWin.h b/Source/core/platform/chromium/ScrollbarThemeChromiumWin.h
index 1ea5c09..ba8deaf 100644
--- a/Source/core/platform/chromium/ScrollbarThemeChromiumWin.h
+++ b/Source/core/platform/chromium/ScrollbarThemeChromiumWin.h
@@ -34,24 +34,26 @@
 #include "core/platform/chromium/ScrollbarThemeChromium.h"
 
 namespace WebCore {
-    class ScrollbarThemeChromiumWin : public ScrollbarThemeChromium {
-    public:
-        virtual int scrollbarThickness(ScrollbarControlSize);
-        virtual bool invalidateOnMouseEnterExit();
-        virtual bool shouldSnapBackToDragOrigin(ScrollbarThemeClient*, const PlatformMouseEvent&);
 
-    protected:
-        virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-        virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-        virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-        virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-        virtual IntSize buttonSize(ScrollbarThemeClient*);
+class ScrollbarThemeChromiumWin : public ScrollbarThemeChromium {
+public:
+    virtual int scrollbarThickness(ScrollbarControlSize) OVERRIDE;
+    virtual bool invalidateOnMouseEnterExit() OVERRIDE;
+    virtual bool shouldSnapBackToDragOrigin(ScrollbarThemeClient*, const PlatformMouseEvent&) OVERRIDE;
 
-    private:
-        int getThemeState(ScrollbarThemeClient*, ScrollbarPart) const;
-        int getThemeArrowState(ScrollbarThemeClient*, ScrollbarPart) const;
-        int getClassicThemeState(ScrollbarThemeClient*, ScrollbarPart) const;
-    };
+protected:
+    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) OVERRIDE;
+    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) OVERRIDE;
+    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
+    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) OVERRIDE;
+    virtual IntSize buttonSize(ScrollbarThemeClient*) OVERRIDE;
+
+private:
+    int getThemeState(ScrollbarThemeClient*, ScrollbarPart) const;
+    int getThemeArrowState(ScrollbarThemeClient*, ScrollbarPart) const;
+    int getClassicThemeState(ScrollbarThemeClient*, ScrollbarPart) const;
+};
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/platform/chromium/support/WebCString.cpp b/Source/core/platform/chromium/support/WebCString.cpp
index 4077ca3..a48abb4 100644
--- a/Source/core/platform/chromium/support/WebCString.cpp
+++ b/Source/core/platform/chromium/support/WebCString.cpp
@@ -34,6 +34,7 @@
 
 #include "public/platform/WebString.h"
 #include "wtf/text/CString.h"
+#include <string.h>
 
 namespace WebKit {
 
diff --git a/Source/core/platform/chromium/support/WebData.cpp b/Source/core/platform/chromium/support/WebData.cpp
index 87d2baf..737bad7 100644
--- a/Source/core/platform/chromium/support/WebData.cpp
+++ b/Source/core/platform/chromium/support/WebData.cpp
@@ -92,6 +92,11 @@
     return PassRefPtr<SharedBuffer>(const_cast<WebDataPrivate*>(m_private));
 }
 
+WebData::operator RefPtr<SharedBuffer>() const
+{
+    return PassRefPtr<SharedBuffer>(const_cast<WebDataPrivate*>(m_private));
+}
+
 void WebData::assign(WebDataPrivate* p)
 {
     // p is already ref'd for us by the caller
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
index e9332f6..849732a 100644
--- a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
+++ b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
@@ -27,7 +27,7 @@
 
 #include "core/platform/chromium/support/WebScrollbarThemeGeometryNative.h"
 
-#include "core/platform/ScrollbarThemeComposite.h"
+#include "core/platform/ScrollbarTheme.h"
 #include "core/platform/chromium/support/WebScrollbarThemeClientImpl.h"
 #include "public/platform/WebScrollbar.h"
 
@@ -35,12 +35,12 @@
 
 namespace WebKit {
 
-PassOwnPtr<WebKit::WebScrollbarThemeGeometryNative> WebScrollbarThemeGeometryNative::create(WebCore::ScrollbarThemeComposite* theme)
+PassOwnPtr<WebKit::WebScrollbarThemeGeometryNative> WebScrollbarThemeGeometryNative::create(WebCore::ScrollbarTheme* theme)
 {
     return adoptPtr(new WebScrollbarThemeGeometryNative(theme));
 }
 
-WebScrollbarThemeGeometryNative::WebScrollbarThemeGeometryNative(WebCore::ScrollbarThemeComposite* theme)
+WebScrollbarThemeGeometryNative::WebScrollbarThemeGeometryNative(WebCore::ScrollbarTheme* theme)
     : m_theme(theme)
 {
 }
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
index 3c83bdd..bd46129 100644
--- a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
+++ b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
@@ -31,7 +31,7 @@
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
-class ScrollbarThemeComposite;
+class ScrollbarTheme;
 }
 
 namespace WebKit {
@@ -40,7 +40,7 @@
 
 class WebScrollbarThemeGeometryNative : public WebScrollbarThemeGeometry {
 public:
-    static PassOwnPtr<WebScrollbarThemeGeometryNative> create(WebCore::ScrollbarThemeComposite*);
+    static PassOwnPtr<WebScrollbarThemeGeometryNative> create(WebCore::ScrollbarTheme*);
 
     // WebScrollbarThemeGeometry overrides
     virtual WebScrollbarThemeGeometryNative* clone() const OVERRIDE;
@@ -62,12 +62,12 @@
     virtual void splitTrack(WebScrollbar*, const WebRect& track, WebRect& startTrack, WebRect& thumb, WebRect& endTrack) OVERRIDE;
 
 private:
-    explicit WebScrollbarThemeGeometryNative(WebCore::ScrollbarThemeComposite*);
+    explicit WebScrollbarThemeGeometryNative(WebCore::ScrollbarTheme*);
 
     // The theme is not owned by this class. It is assumed that the theme is a
     // static pointer and its lifetime is essentially infinite. Only thread-safe
     // functions on the theme can be called by this theme.
-    WebCore::ScrollbarThemeComposite* m_theme;
+    WebCore::ScrollbarTheme* m_theme;
 };
 
 } // namespace WebKit
diff --git a/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp b/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp
index f6e2136..34451aa 100644
--- a/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp
+++ b/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp
@@ -80,10 +80,10 @@
     context->endTransparencyLayer();
 }
 
-void CrossfadeGeneratedImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode)
+void CrossfadeGeneratedImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
 {
     GraphicsContextStateSaver stateSaver(*context);
-    context->setCompositeOperation(compositeOp);
+    context->setCompositeOperation(compositeOp, blendMode);
     context->clip(dstRect);
     context->translate(dstRect.x(), dstRect.y());
     if (dstRect.size() != srcRect.size())
@@ -93,7 +93,7 @@
     drawCrossfade(context);
 }
 
-void CrossfadeGeneratedImage::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale, const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, BlendMode)
+void CrossfadeGeneratedImage::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale, const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, BlendMode blendMode)
 {
     OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(m_size, 1, context->isAccelerated() ? Accelerated : Unaccelerated);
     if (!imageBuffer)
@@ -104,7 +104,7 @@
     drawCrossfade(graphicsContext);
 
     // Tile the image buffer into the context.
-    imageBuffer->drawPattern(context, srcRect, scale, phase, compositeOp, dstRect);
+    imageBuffer->drawPattern(context, srcRect, scale, phase, compositeOp, dstRect, blendMode);
 }
 
 }
diff --git a/Source/core/platform/graphics/FontCache.cpp b/Source/core/platform/graphics/FontCache.cpp
index 55cc917..aafd75f 100644
--- a/Source/core/platform/graphics/FontCache.cpp
+++ b/Source/core/platform/graphics/FontCache.cpp
@@ -176,7 +176,7 @@
     return emptyAtom;
 }
 
-FontPlatformData* FontCache::getCachedFontPlatformData(const FontDescription& fontDescription,
+FontPlatformData* FontCache::getFontResourcePlatformData(const FontDescription& fontDescription,
                                                        const AtomicString& passedFamilyName,
                                                        bool checkingAlternateName)
 {
@@ -214,7 +214,7 @@
         // e.g., Arial/Helvetica, Courier/Courier New, etc.  Try looking up the font under the aliased name.
         const AtomicString& alternateName = alternateFamilyName(familyName);
         if (!alternateName.isEmpty())
-            result = getCachedFontPlatformData(fontDescription, alternateName, true);
+            result = getFontResourcePlatformData(fontDescription, alternateName, true);
         if (result)
             gFontPlatformDataCache->set(key, new FontPlatformData(*result)); // Cache the result under the old name.
     }
@@ -291,16 +291,16 @@
 #endif
 static ListHashSet<RefPtr<SimpleFontData> >* gInactiveFontData = 0;
 
-PassRefPtr<SimpleFontData> FontCache::getCachedFontData(const FontDescription& fontDescription, const AtomicString& family, bool checkingAlternateName, ShouldRetain shouldRetain)
+PassRefPtr<SimpleFontData> FontCache::getFontResourceData(const FontDescription& fontDescription, const AtomicString& family, bool checkingAlternateName, ShouldRetain shouldRetain)
 {
-    FontPlatformData* platformData = getCachedFontPlatformData(fontDescription, family, checkingAlternateName);
+    FontPlatformData* platformData = getFontResourcePlatformData(fontDescription, family, checkingAlternateName);
     if (!platformData)
         return 0;
 
-    return getCachedFontData(platformData, shouldRetain);
+    return getFontResourceData(platformData, shouldRetain);
 }
 
-PassRefPtr<SimpleFontData> FontCache::getCachedFontData(const FontPlatformData* platformData, ShouldRetain shouldRetain)
+PassRefPtr<SimpleFontData> FontCache::getFontResourceData(const FontPlatformData* platformData, ShouldRetain shouldRetain)
 {
     if (!platformData)
         return 0;
@@ -470,7 +470,7 @@
                 result = fontSelector->getFontData(font.fontDescription(), currFamily->family());
 
             if (!result)
-                result = getCachedFontData(font.fontDescription(), currFamily->family());
+                result = getFontResourceData(font.fontDescription(), currFamily->family());
         }
         currFamily = currFamily->next();
     }
@@ -564,14 +564,14 @@
     FontPlatformData* fontPlatformData = 0;
     switch (description.genericFamily()) {
     case FontDescription::SerifFamily:
-        fontPlatformData = getCachedFontPlatformData(description, serifStr);
+        fontPlatformData = getFontResourcePlatformData(description, serifStr);
         break;
     case FontDescription::MonospaceFamily:
-        fontPlatformData = getCachedFontPlatformData(description, monospaceStr);
+        fontPlatformData = getFontResourcePlatformData(description, monospaceStr);
         break;
     case FontDescription::SansSerifFamily:
     default:
-        fontPlatformData = getCachedFontPlatformData(description, sansStr);
+        fontPlatformData = getFontResourcePlatformData(description, sansStr);
         break;
     }
 
diff --git a/Source/core/platform/graphics/FontCache.h b/Source/core/platform/graphics/FontCache.h
index cf43ba2..b268374 100644
--- a/Source/core/platform/graphics/FontCache.h
+++ b/Source/core/platform/graphics/FontCache.h
@@ -75,7 +75,7 @@
 
     void getTraitsInFamily(const AtomicString&, Vector<unsigned>&);
 
-    PassRefPtr<SimpleFontData> getCachedFontData(const FontDescription&, const AtomicString&, bool checkingAlternateName = false, ShouldRetain = Retain);
+    PassRefPtr<SimpleFontData> getFontResourceData(const FontDescription&, const AtomicString&, bool checkingAlternateName = false, ShouldRetain = Retain);
     PassRefPtr<SimpleFontData> getLastResortFallbackFont(const FontDescription&, ShouldRetain = Retain);
     SimpleFontData* getNonRetainedLastResortFallbackFont(const FontDescription&);
 
@@ -120,13 +120,13 @@
     void purgeInactiveFontDataIfNeeded();
 
     // FIXME: This method should eventually be removed.
-    FontPlatformData* getCachedFontPlatformData(const FontDescription&, const AtomicString& family, bool checkingAlternateName = false);
+    FontPlatformData* getFontResourcePlatformData(const FontDescription&, const AtomicString& family, bool checkingAlternateName = false);
 
     // These methods are implemented by each platform.
     PassRefPtr<SimpleFontData> getSimilarFontPlatformData(const Font&);
     FontPlatformData* createFontPlatformData(const FontDescription&, const AtomicString& family);
 
-    PassRefPtr<SimpleFontData> getCachedFontData(const FontPlatformData*, ShouldRetain = Retain);
+    PassRefPtr<SimpleFontData> getFontResourceData(const FontPlatformData*, ShouldRetain = Retain);
     const FontPlatformData* getFallbackFontData(const FontDescription&);
 
     // Don't purge if this count is > 0;
@@ -135,7 +135,7 @@
 #if OS(DARWIN) || OS(ANDROID)
     friend class ComplexTextController;
 #endif
-    friend class SimpleFontData; // For getCachedFontData(const FontPlatformData*)
+    friend class SimpleFontData; // For getFontResourceData(const FontPlatformData*)
     friend class FontFallbackList;
 };
 
diff --git a/Source/core/platform/graphics/FontFallbackList.cpp b/Source/core/platform/graphics/FontFallbackList.cpp
index f04fa94..e3405e5 100644
--- a/Source/core/platform/graphics/FontFallbackList.cpp
+++ b/Source/core/platform/graphics/FontFallbackList.cpp
@@ -117,7 +117,7 @@
 {
     m_familyIndex = cAllFamiliesScanned;
     ASSERT(fontCache()->generation() == m_generation);
-    RefPtr<FontData> fontData = fontCache()->getCachedFontData(&platformData);
+    RefPtr<FontData> fontData = fontCache()->getFontResourceData(&platformData);
     m_fontList.append(fontData);
 }
 
diff --git a/Source/core/platform/graphics/GeneratorGeneratedImage.cpp b/Source/core/platform/graphics/GeneratorGeneratedImage.cpp
index 56031ad..149bc1b 100644
--- a/Source/core/platform/graphics/GeneratorGeneratedImage.cpp
+++ b/Source/core/platform/graphics/GeneratorGeneratedImage.cpp
@@ -139,7 +139,7 @@
     }
 
     // Tile the image buffer into the context.
-    m_cachedImageBuffer->drawPattern(destContext, adjustedSrcRect, scaleWithoutCTM, phase, compositeOp, destRect);
+    m_cachedImageBuffer->drawPattern(destContext, adjustedSrcRect, scaleWithoutCTM, phase, compositeOp, destRect, blendMode);
     m_cacheTimer.restart();
 }
 
diff --git a/Source/core/platform/graphics/GraphicsContext3D.cpp b/Source/core/platform/graphics/GraphicsContext3D.cpp
index 92cc549..5e2b93c 100644
--- a/Source/core/platform/graphics/GraphicsContext3D.cpp
+++ b/Source/core/platform/graphics/GraphicsContext3D.cpp
@@ -29,8 +29,6 @@
 
 #include "core/platform/graphics/GraphicsContext3D.h"
 
-#include "GrContext.h"
-#include "GrGLInterface.h"
 #include "core/html/ImageData.h"
 #include "core/html/canvas/CheckedInt.h"
 #include "core/platform/graphics/Extensions3D.h"
@@ -40,6 +38,8 @@
 #include "core/platform/graphics/ImageObserver.h"
 #include "core/platform/graphics/gpu/DrawingBuffer.h"
 #include "core/platform/image-decoders/ImageDecoder.h"
+#include "third_party/skia/include/gpu/GrContext.h"
+#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
 #include "wtf/CPU.h"
 #include "wtf/OwnArrayPtr.h"
 #include "wtf/PassOwnArrayPtr.h"
@@ -839,37 +839,6 @@
     return true;
 }
 
-unsigned GraphicsContext3D::getClearBitsByAttachmentType(GC3Denum attachment)
-{
-    switch (attachment) {
-    case GraphicsContext3D::COLOR_ATTACHMENT0:
-    case Extensions3D::COLOR_ATTACHMENT1_EXT:
-    case Extensions3D::COLOR_ATTACHMENT2_EXT:
-    case Extensions3D::COLOR_ATTACHMENT3_EXT:
-    case Extensions3D::COLOR_ATTACHMENT4_EXT:
-    case Extensions3D::COLOR_ATTACHMENT5_EXT:
-    case Extensions3D::COLOR_ATTACHMENT6_EXT:
-    case Extensions3D::COLOR_ATTACHMENT7_EXT:
-    case Extensions3D::COLOR_ATTACHMENT8_EXT:
-    case Extensions3D::COLOR_ATTACHMENT9_EXT:
-    case Extensions3D::COLOR_ATTACHMENT10_EXT:
-    case Extensions3D::COLOR_ATTACHMENT11_EXT:
-    case Extensions3D::COLOR_ATTACHMENT12_EXT:
-    case Extensions3D::COLOR_ATTACHMENT13_EXT:
-    case Extensions3D::COLOR_ATTACHMENT14_EXT:
-    case Extensions3D::COLOR_ATTACHMENT15_EXT:
-        return GraphicsContext3D::COLOR_BUFFER_BIT;
-    case GraphicsContext3D::DEPTH_ATTACHMENT:
-        return GraphicsContext3D::DEPTH_BUFFER_BIT;
-    case GraphicsContext3D::STENCIL_ATTACHMENT:
-        return GraphicsContext3D::STENCIL_BUFFER_BIT;
-    case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
-        return GraphicsContext3D::DEPTH_BUFFER_BIT | GraphicsContext3D::STENCIL_BUFFER_BIT;
-    default:
-        return 0;
-    }
-}
-
 unsigned GraphicsContext3D::getClearBitsByFormat(GC3Denum format)
 {
     switch (format) {
diff --git a/Source/core/platform/graphics/GraphicsContext3D.h b/Source/core/platform/graphics/GraphicsContext3D.h
index 755aa28..be085a1 100644
--- a/Source/core/platform/graphics/GraphicsContext3D.h
+++ b/Source/core/platform/graphics/GraphicsContext3D.h
@@ -703,7 +703,6 @@
     // determine this.
     Extensions3D* getExtensions();
 
-    static unsigned getClearBitsByAttachmentType(GC3Denum);
     static unsigned getClearBitsByFormat(GC3Denum);
 
     enum ChannelBits {
diff --git a/Source/core/platform/graphics/GraphicsContextAnnotation.cpp b/Source/core/platform/graphics/GraphicsContextAnnotation.cpp
index 0a8c387..1ca9824 100644
--- a/Source/core/platform/graphics/GraphicsContextAnnotation.cpp
+++ b/Source/core/platform/graphics/GraphicsContextAnnotation.cpp
@@ -127,10 +127,10 @@
     list.clear();
 
     if (m_rendererName)
-        list.append(std::make_pair(AnnotationKeyRendererName, ASCIILiteral(m_rendererName)));
+        list.append(std::make_pair(AnnotationKeyRendererName, m_rendererName));
 
     if (m_paintPhase)
-        list.append(std::make_pair(AnnotationKeyPaintPhase, ASCIILiteral(m_paintPhase)));
+        list.append(std::make_pair(AnnotationKeyPaintPhase, m_paintPhase));
 
     if (!m_elementId.isEmpty())
         list.append(std::make_pair(AnnotationKeyElementId, m_elementId));
diff --git a/Source/core/platform/graphics/GraphicsContextAnnotation.h b/Source/core/platform/graphics/GraphicsContextAnnotation.h
index 22684b5..f30a38d 100644
--- a/Source/core/platform/graphics/GraphicsContextAnnotation.h
+++ b/Source/core/platform/graphics/GraphicsContextAnnotation.h
@@ -62,8 +62,8 @@
 public:
     GraphicsContextAnnotation(const PaintInfo&, const RenderObject*);
 
-    String rendererName() const { return ASCIILiteral(m_rendererName); }
-    String paintPhase() const { return ASCIILiteral(m_paintPhase); }
+    String rendererName() const { return m_rendererName; }
+    String paintPhase() const { return m_paintPhase; }
     String elementId() const { return m_elementId; }
     String elementClass() const { return m_elementClass; }
     String elementTag() const { return m_elementTag; }
diff --git a/Source/core/platform/graphics/GraphicsLayer.cpp b/Source/core/platform/graphics/GraphicsLayer.cpp
index 5673bb8..cce5cba 100644
--- a/Source/core/platform/graphics/GraphicsLayer.cpp
+++ b/Source/core/platform/graphics/GraphicsLayer.cpp
@@ -1236,8 +1236,8 @@
             return false;
         }
         SkiaImageFilterBuilder builder;
-        SkAutoTUnref<SkImageFilter> imageFilter(builder.build(filters));
-        m_layer->layer()->setFilter(imageFilter);
+        RefPtr<SkImageFilter> imageFilter = builder.build(filters);
+        m_layer->layer()->setFilter(imageFilter.get());
     } else {
         OwnPtr<WebFilterOperations> webFilters = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
         if (!copyWebCoreFilterOperationsToWebFilterOperations(filters, *webFilters)) {
diff --git a/Source/core/platform/graphics/Image.h b/Source/core/platform/graphics/Image.h
index 21923b2..9e90ab3 100644
--- a/Source/core/platform/graphics/Image.h
+++ b/Source/core/platform/graphics/Image.h
@@ -102,7 +102,7 @@
     virtual void stopAnimation() {}
     virtual void resetAnimation() {}
 
-    // Typically the CachedImage that owns us.
+    // Typically the ImageResource that owns us.
     ImageObserver* imageObserver() const { return m_imageObserver; }
     void setImageObserver(ImageObserver* observer) { m_imageObserver = observer; }
 
@@ -127,7 +127,7 @@
     virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator, BlendMode) = 0;
     virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator, BlendMode, RespectImageOrientationEnum);
     void drawTiled(GraphicsContext*, const FloatRect& dstRect, const FloatPoint& srcPoint, const FloatSize& tileSize,
-        CompositeOperator , BlendMode);
+        CompositeOperator, BlendMode);
     void drawTiled(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, const FloatSize& tileScaleFactor, TileRule hRule, TileRule vRule, CompositeOperator);
 
     // Supporting tiled drawing
diff --git a/Source/core/platform/graphics/ImageBuffer.cpp b/Source/core/platform/graphics/ImageBuffer.cpp
index 86fde96..48f2f54 100644
--- a/Source/core/platform/graphics/ImageBuffer.cpp
+++ b/Source/core/platform/graphics/ImageBuffer.cpp
@@ -254,14 +254,14 @@
 }
 
 void ImageBuffer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale,
-    const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect)
+    const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect, BlendMode blendMode)
 {
     if (!isValid())
         return;
 
     const SkBitmap& bitmap = *m_context->bitmap();
     RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
-    image->drawPattern(context, srcRect, scale, phase, op, destRect);
+    image->drawPattern(context, srcRect, scale, phase, op, destRect, blendMode);
 }
 
 void ImageBuffer::transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace)
diff --git a/Source/core/platform/graphics/ImageBuffer.h b/Source/core/platform/graphics/ImageBuffer.h
index 935c911..b4c0af9 100644
--- a/Source/core/platform/graphics/ImageBuffer.h
+++ b/Source/core/platform/graphics/ImageBuffer.h
@@ -134,7 +134,7 @@
     bool isValid() const;
 
     void draw(GraphicsContext*, const FloatRect&, const FloatRect& = FloatRect(0, 0, -1, -1), CompositeOperator = CompositeSourceOver, BlendMode = BlendModeNormal, bool useLowQualityScale = false);
-    void drawPattern(GraphicsContext*, const FloatRect&, const FloatSize&, const FloatPoint&, CompositeOperator, const FloatRect&);
+    void drawPattern(GraphicsContext*, const FloatRect&, const FloatSize&, const FloatPoint&, CompositeOperator, const FloatRect&, BlendMode);
 
     friend class GraphicsContext;
     friend class GeneratedImage;
diff --git a/Source/core/platform/graphics/RoundedRect.cpp b/Source/core/platform/graphics/RoundedRect.cpp
index 8eab02d..4ef8261 100644
--- a/Source/core/platform/graphics/RoundedRect.cpp
+++ b/Source/core/platform/graphics/RoundedRect.cpp
@@ -27,6 +27,7 @@
 
 #include "config.h"
 #include "core/platform/graphics/RoundedRect.h"
+#include "wtf/Assertions.h"
 
 #include <algorithm>
 
@@ -150,6 +151,16 @@
 {
 }
 
+IntRect RoundedRect::radiusCenterRect() const
+{
+    ASSERT(isRenderable());
+    int minX = m_rect.x() + max(m_radii.topLeft().width(), m_radii.bottomLeft().width());
+    int minY = m_rect.y() + max(m_radii.topLeft().height(), m_radii.topRight().height());
+    int maxX = m_rect.maxX() - max(m_radii.topRight().width(), m_radii.bottomRight().width());
+    int maxY = m_rect.maxY() - max(m_radii.bottomLeft().height(), m_radii.bottomRight().height());
+    return IntRect(minX, minY, maxX - minX, maxY - minY);
+}
+
 void RoundedRect::includeLogicalEdges(const Radii& edges, bool isHorizontal, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
 {
     m_radii.includeLogicalEdges(edges, isHorizontal, includeLogicalLeftEdge, includeLogicalRightEdge);
diff --git a/Source/core/platform/graphics/RoundedRect.h b/Source/core/platform/graphics/RoundedRect.h
index 8dde238..80c84f4 100644
--- a/Source/core/platform/graphics/RoundedRect.h
+++ b/Source/core/platform/graphics/RoundedRect.h
@@ -82,6 +82,9 @@
     bool isRounded() const { return !m_radii.isZero(); }
     bool isEmpty() const { return m_rect.isEmpty(); }
 
+    // Returns a quickly computed rect enclosed by the rounded rect.
+    IntRect radiusCenterRect() const;
+
     void setRect(const IntRect& rect) { m_rect = rect; }
     void setRadii(const Radii& radii) { m_radii = radii; }
 
diff --git a/Source/core/platform/graphics/RoundedRectTest.cpp b/Source/core/platform/graphics/RoundedRectTest.cpp
new file mode 100644
index 0000000..2bdccb8
--- /dev/null
+++ b/Source/core/platform/graphics/RoundedRectTest.cpp
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/platform/graphics/RoundedRect.h"
+
+#include "core/platform/graphics/IntRect.h"
+
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace WebCore {
+
+// FIXME: Move this somewhere more generic.
+void PrintTo(const IntRect& rect, std::ostream* os)
+{
+    *os << "IntRect("
+        << rect.x() << ", "
+        << rect.y() << ", "
+        << rect.width() << ", "
+        << rect.height() << ")";
+}
+
+} // namespace WebCore
+
+namespace {
+
+TEST(RoundedRectTest, RadiusCenterRectZeroRadius)
+{
+    RoundedRect rr(100, 200, 300, 400);
+    EXPECT_TRUE(rr.rect().contains(rr.radiusCenterRect()));
+    EXPECT_EQ(IntRect(100, 200, 300, 400), rr.radiusCenterRect());
+}
+
+TEST(RoundedRectTest, RadiusCenterRectEqualRadius)
+{
+    RoundedRect rr(IntRect(100, 200, 300, 400), IntSize(10, 10), IntSize(10, 10), IntSize(10, 10), IntSize(10, 10));
+    EXPECT_TRUE(rr.rect().contains(rr.radiusCenterRect()));
+    EXPECT_EQ(IntRect(110, 210, 280, 380), rr.radiusCenterRect());
+}
+
+TEST(RoundedRectTest, RadiusCenterRectUnequalRadius)
+{
+    RoundedRect rr(IntRect(100, 200, 300, 400), IntSize(5, 5), IntSize(10, 10), IntSize(15, 15), IntSize(20, 20));
+    EXPECT_TRUE(rr.rect().contains(rr.radiusCenterRect()));
+    EXPECT_EQ(IntRect(115, 210, 265, 370), rr.radiusCenterRect());
+}
+
+TEST(RoundedRectTest, RadiusCenterRectElliptical)
+{
+    RoundedRect rr(IntRect(100, 200, 300, 400), IntSize(20, 10), IntSize(20, 10), IntSize(10, 20), IntSize(10, 20));
+    EXPECT_TRUE(rr.rect().contains(rr.radiusCenterRect()));
+    EXPECT_EQ(IntRect(120, 210, 260, 370), rr.radiusCenterRect());
+}
+
+} // namespace
diff --git a/Source/core/platform/graphics/SourceBufferPrivate.h b/Source/core/platform/graphics/SourceBufferPrivate.h
index 7e3bdcf..f3bf4a9 100644
--- a/Source/core/platform/graphics/SourceBufferPrivate.h
+++ b/Source/core/platform/graphics/SourceBufferPrivate.h
@@ -44,6 +44,8 @@
     virtual void abort() = 0;
     virtual void remove(double start, double end) = 0;
     virtual bool setTimestampOffset(double) = 0;
+    virtual void setAppendWindowStart(double) = 0;
+    virtual void setAppendWindowEnd(double) = 0;
     virtual void removedFromMediaSource() = 0;
 };
 
diff --git a/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp b/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
index 2063711..58768f9 100644
--- a/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
+++ b/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
@@ -30,6 +30,7 @@
 #include "core/platform/graphics/FloatSize.h"
 #include "core/platform/graphics/GraphicsLayer.h"
 #include "core/platform/graphics/chromium/TransformSkMatrix44Conversions.h"
+#include "core/platform/graphics/transforms/InterpolatedTransformOperation.h"
 #include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
 #include "core/platform/graphics/transforms/MatrixTransformOperation.h"
 #include "core/platform/graphics/transforms/PerspectiveTransformOperation.h"
@@ -114,6 +115,12 @@
             webTransformOperations->appendPerspective(floatValueForLength(transform->perspective(), 0));
             break;
         }
+        case TransformOperation::Interpolated: {
+            TransformationMatrix m;
+            transformOperations.operations()[j]->apply(m, boxSize);
+            webTransformOperations->appendMatrix(TransformSkMatrix44Conversions::convert(m));
+            break;
+        }
         case TransformOperation::Identity:
             webTransformOperations->appendIdentity();
             break;
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
index 3e9a705..415175a 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
@@ -65,7 +65,7 @@
     SkAutoTUnref<SkSurface> surface(createSurface(context.get(), size));
     if (!surface.get())
         return PassOwnPtr<Canvas2DLayerBridge>();
-    SkDeferredCanvas* canvas = new SkDeferredCanvas(surface);
+    SkDeferredCanvas* canvas = SkDeferredCanvas::Create(surface.get());
     OwnPtr<Canvas2DLayerBridge> layerBridge = adoptPtr(new Canvas2DLayerBridge(context, canvas, opacityMode));
     return layerBridge.release();
 }
@@ -185,7 +185,11 @@
 
 WebGraphicsContext3D* Canvas2DLayerBridge::context()
 {
-    isValid(); // To ensure rate limiter is disabled if context is lost.
+    // Check on m_layer is necessary because context() may be called during
+    // the destruction of m_layer
+    if (m_layer) {
+        isValid(); // To ensure rate limiter is disabled if context is lost.
+    }
     return m_context->webContext();
 }
 
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp b/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
index b7c83c4..7af3be0 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
@@ -27,6 +27,7 @@
 #include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
 
 #include "SkDeferredCanvas.h"
+#include "SkSurface.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/tests/FakeWebGraphicsContext3D.h"
 #include "public/platform/Platform.h"
@@ -76,12 +77,17 @@
 
         MockCanvasContext& mainMock = *static_cast<MockCanvasContext*>(mainContext->webContext());
 
-        SkDevice device(SkBitmap::kARGB_8888_Config, 300, 150);
-        SkDeferredCanvas canvas(&device);
+        SkImage::Info info = {
+            300,
+            150,
+            SkImage::kPMColor_ColorType,
+            SkImage::kPremul_AlphaType,
+        };
+        SkAutoTUnref<SkDeferredCanvas> canvas(SkDeferredCanvas::Create(SkSurface::NewRaster(info)));
 
         ::testing::Mock::VerifyAndClearExpectations(&mainMock);
 
-        OwnPtr<Canvas2DLayerBridge> bridge = FakeCanvas2DLayerBridge::create(mainContext.release(), &canvas, Canvas2DLayerBridge::NonOpaque);
+        OwnPtr<Canvas2DLayerBridge> bridge = FakeCanvas2DLayerBridge::create(mainContext.release(), canvas.get(), Canvas2DLayerBridge::NonOpaque);
 
         ::testing::Mock::VerifyAndClearExpectations(&mainMock);
 
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp b/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
index 83dfa09..33e9ca6 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
@@ -27,6 +27,7 @@
 #include "core/platform/graphics/chromium/Canvas2DLayerManager.h"
 
 #include "SkDevice.h"
+#include "SkSurface.h"
 #include "core/platform/graphics/GraphicsContext3D.h"
 #include "core/tests/FakeWebGraphicsContext3D.h"
 #include "public/platform/Platform.h"
@@ -90,8 +91,13 @@
 
 static PassOwnPtr<SkDeferredCanvas> createCanvas(GraphicsContext3D* context)
 {
-    SkAutoTUnref<SkDevice> device(new SkDevice(SkBitmap::kARGB_8888_Config, 1, 1));
-    return adoptPtr(new SkDeferredCanvas(device.get()));
+    SkImage::Info info = {
+        1,
+        1,
+        SkImage::kPMColor_ColorType,
+        SkImage::kPremul_AlphaType,
+    };
+    return adoptPtr(SkDeferredCanvas::Create(SkSurface::NewRaster(info)));
 }
 
 class Canvas2DLayerManagerTest : public Test {
diff --git a/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp b/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
index d3546f6..79d8283 100644
--- a/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
+++ b/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
@@ -102,7 +102,7 @@
     SkString skiaFamilyName;
     if (!SkGetFallbackFamilyNameForChar(c, &skiaFamilyName) || skiaFamilyName.isEmpty())
         return 0;
-    return getCachedFontData(getCachedFontPlatformData(font.fontDescription(), AtomicString(skiaFamilyName.c_str()), DoNotRetain), DoNotRetain);
+    return getFontResourceData(getFontResourcePlatformData(font.fontDescription(), AtomicString(skiaFamilyName.c_str()), DoNotRetain), DoNotRetain);
 }
 
 PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
@@ -114,7 +114,7 @@
 {
     const FontPlatformData* fontPlatformData = getFallbackFontData(description);
     ASSERT(fontPlatformData);
-    return getCachedFontData(fontPlatformData, shouldRetain);
+    return getFontResourceData(fontPlatformData, shouldRetain);
 }
 
 void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
diff --git a/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp b/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
index 55f2ff1..1bd99e9 100644
--- a/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
@@ -319,7 +319,7 @@
 // Tries the given font and save it |outFontFamilyName| if it succeeds.
 PassRefPtr<SimpleFontData> FontCache::fontDataFromDescriptionAndLogFont(const FontDescription& fontDescription, ShouldRetain shouldRetain, const LOGFONT& font, wchar_t* outFontFamilyName)
 {
-    RefPtr<SimpleFontData> fontData = getCachedFontData(fontDescription, font.lfFaceName, false, shouldRetain);
+    RefPtr<SimpleFontData> fontData = getFontResourceData(fontDescription, font.lfFaceName, false, shouldRetain);
     if (fontData)
         memcpy(outFontFamilyName, font.lfFaceName, sizeof(font.lfFaceName));
     return fontData.release();
@@ -445,7 +445,7 @@
     const wchar_t* family = getFallbackFamily(codeUnits, codeUnitsLength, fontDescription.genericFamily(), &c, &script);
     FontPlatformData* data = 0;
     if (family)
-        data = getCachedFontPlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)), false);
+        data = getFontResourcePlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)), false);
 
     // Last resort font list : PanUnicode. CJK fonts have a pretty
     // large repertoire. Eventually, we need to scan all the fonts
@@ -505,7 +505,7 @@
     int i;
     for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) {
         family = panUniFonts[i];
-        data = getCachedFontPlatformData(font.fontDescription(), AtomicString(family, wcslen(family)));
+        data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)));
     }
     // When i-th font (0-base) in |panUniFonts| contains a character and
     // we get out of the loop, |i| will be |i + 1|. That is, if only the
@@ -513,7 +513,7 @@
     // So, we have to use '<=" rather than '<' to see if we found a font
     // covering the character.
     if (i <= numFonts)
-        return getCachedFontData(data, DoNotRetain);
+        return getFontResourceData(data, DoNotRetain);
 
     return 0;
 
@@ -541,7 +541,7 @@
     else if (generic == FontDescription::MonospaceFamily)
         fontStr = courierStr;
 
-    RefPtr<SimpleFontData> simpleFont = getCachedFontData(description, fontStr, false, shouldRetain);
+    RefPtr<SimpleFontData> simpleFont = getFontResourceData(description, fontStr, false, shouldRetain);
     if (simpleFont)
         return simpleFont.release();
 
@@ -550,7 +550,7 @@
     // to a static variable and use it to prevent trying system fonts again.
     static wchar_t fallbackFontName[LF_FACESIZE] = {0};
     if (fallbackFontName[0])
-        return getCachedFontData(description, fallbackFontName, false, shouldRetain);
+        return getFontResourceData(description, fallbackFontName, false, shouldRetain);
 
     // Fall back to the DEFAULT_GUI_FONT if no known Unicode fonts are available.
     if (HFONT defaultGUIFont = static_cast<HFONT>(GetStockObject(DEFAULT_GUI_FONT))) {
diff --git a/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp b/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp
index 8c3ad27..88fc7a5 100644
--- a/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp
+++ b/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp
@@ -38,7 +38,7 @@
     , m_frameIndex(index)
     , m_scaledSize(scaledSize)
     , m_scaledSubset(scaledSubset)
-    , m_lockedCachedImage(0)
+    , m_lockedImageResource(0)
 {
 }
 
@@ -76,29 +76,29 @@
 {
     TRACE_EVENT_ASYNC_BEGIN0("webkit", "LazyDecodingPixelRef::lockPixels", this);
 
-    ASSERT(!m_lockedCachedImage);
+    ASSERT(!m_lockedImageResource);
 
-    if (!ImageDecodingStore::instance()->lockCache(m_frameGenerator.get(), m_scaledSize, m_frameIndex, &m_lockedCachedImage))
-        m_lockedCachedImage = 0;
+    if (!ImageDecodingStore::instance()->lockCache(m_frameGenerator.get(), m_scaledSize, m_frameIndex, &m_lockedImageResource))
+        m_lockedImageResource = 0;
 
     // Use ImageFrameGenerator to generate the image. It will lock the cache
     // entry for us.
-    if (!m_lockedCachedImage)
-        m_lockedCachedImage = m_frameGenerator->decodeAndScale(m_scaledSize, m_frameIndex);
+    if (!m_lockedImageResource)
+        m_lockedImageResource = m_frameGenerator->decodeAndScale(m_scaledSize, m_frameIndex);
 
-    if (!m_lockedCachedImage)
+    if (!m_lockedImageResource)
         return 0;
 
-    ASSERT(!m_lockedCachedImage->bitmap().isNull());
-    ASSERT(m_lockedCachedImage->scaledSize() == m_scaledSize);
-    return m_lockedCachedImage->bitmap().getAddr(m_scaledSubset.x(), m_scaledSubset.y());
+    ASSERT(!m_lockedImageResource->bitmap().isNull());
+    ASSERT(m_lockedImageResource->scaledSize() == m_scaledSize);
+    return m_lockedImageResource->bitmap().getAddr(m_scaledSubset.x(), m_scaledSubset.y());
 }
 
 void LazyDecodingPixelRef::onUnlockPixels()
 {
-    if (m_lockedCachedImage) {
-        ImageDecodingStore::instance()->unlockCache(m_frameGenerator.get(), m_lockedCachedImage);
-        m_lockedCachedImage = 0;
+    if (m_lockedImageResource) {
+        ImageDecodingStore::instance()->unlockCache(m_frameGenerator.get(), m_lockedImageResource);
+        m_lockedImageResource = 0;
     }
 
     TRACE_EVENT_ASYNC_END0("webkit", "LazyDecodingPixelRef::lockPixels", this);
diff --git a/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h b/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h
index bb288eb..0ceb7da 100644
--- a/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h
+++ b/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h
@@ -76,7 +76,7 @@
     SkISize m_scaledSize;
     SkIRect m_scaledSubset;
 
-    const ScaledImageFragment* m_lockedCachedImage;
+    const ScaledImageFragment* m_lockedImageResource;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/filters/DropShadowImageFilter.cpp b/Source/core/platform/graphics/filters/DropShadowImageFilter.cpp
deleted file mode 100644
index b43fa22..0000000
--- a/Source/core/platform/graphics/filters/DropShadowImageFilter.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "config.h"
-
-#include "core/platform/graphics/filters/DropShadowImageFilter.h"
-
-#include "SkBitmap.h"
-#include "SkBlurImageFilter.h"
-#include "SkCanvas.h"
-#include "SkColorMatrixFilter.h"
-#include "SkDevice.h"
-#include "SkFlattenableBuffers.h"
-
-namespace WebCore {
-
-DropShadowImageFilter::DropShadowImageFilter(SkScalar dx, SkScalar dy, SkScalar sigma, SkColor color, SkImageFilter* input)
-    : SkImageFilter(input)
-    , m_dx(dx)
-    , m_dy(dy)
-    , m_sigma(sigma)
-    , m_color(color)
-{
-}
-
-DropShadowImageFilter::DropShadowImageFilter(SkFlattenableReadBuffer& buffer) : SkImageFilter(buffer)
-{
-    m_dx = buffer.readScalar();
-    m_dy = buffer.readScalar();
-    m_sigma = buffer.readScalar();
-    m_color = buffer.readColor();
-}
-
-void DropShadowImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const
-{
-    buffer.writeScalar(m_dx);
-    buffer.writeScalar(m_dy);
-    buffer.writeScalar(m_sigma);
-    buffer.writeColor(m_color);
-}
-
-bool DropShadowImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, const SkMatrix& matrix, SkBitmap* result, SkIPoint* loc)
-{
-    SkBitmap src = source;
-    if (getInput(0) && !getInput(0)->filterImage(proxy, source, matrix, &src, loc))
-        return false;
-
-    SkAutoTUnref<SkDevice> device(proxy->createDevice(src.width(), src.height()));
-    SkCanvas canvas(device.get());
-
-    SkAutoTUnref<SkImageFilter> blurFilter(new SkBlurImageFilter(m_sigma, m_sigma));
-    SkAutoTUnref<SkColorFilter> colorFilter(SkColorFilter::CreateModeFilter(m_color, SkXfermode::kSrcIn_Mode));
-    SkPaint paint;
-    paint.setImageFilter(blurFilter.get());
-    paint.setColorFilter(colorFilter.get());
-    paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
-    canvas.saveLayer(0, &paint);
-    canvas.drawBitmap(src, m_dx, -m_dy);
-    canvas.restore();
-    canvas.drawBitmap(src, 0, 0);
-    *result = device.get()->accessBitmap(false);
-    return true;
-}
-
-};
diff --git a/Source/core/platform/graphics/filters/DropShadowImageFilter.h b/Source/core/platform/graphics/filters/DropShadowImageFilter.h
deleted file mode 100644
index 45b117b..0000000
--- a/Source/core/platform/graphics/filters/DropShadowImageFilter.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "SkColor.h"
-#include "SkImageFilter.h"
-#include "SkScalar.h"
-
-namespace WebCore {
-
-class DropShadowImageFilter : public SkImageFilter {
-public:
-    DropShadowImageFilter(SkScalar dx, SkScalar dy, SkScalar sigma, SkColor, SkImageFilter* input = 0);
-    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(DropShadowImageFilter)
-
-protected:
-    explicit DropShadowImageFilter(SkFlattenableReadBuffer&);
-    virtual void flatten(SkFlattenableWriteBuffer&) const OVERRIDE;
-    virtual bool onFilterImage(Proxy*, const SkBitmap& source, const SkMatrix&, SkBitmap* result, SkIPoint* loc) OVERRIDE;
-
-private:
-    SkScalar m_dx, m_dy, m_sigma;
-    SkColor m_color;
-};
-
-};
diff --git a/Source/core/platform/graphics/filters/FEBlend.cpp b/Source/core/platform/graphics/filters/FEBlend.cpp
index b4fb7cb..78d2bec 100644
--- a/Source/core/platform/graphics/filters/FEBlend.cpp
+++ b/Source/core/platform/graphics/filters/FEBlend.cpp
@@ -242,12 +242,12 @@
     return true;
 }
 
-SkImageFilter* FEBlend::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEBlend::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> foreground(builder->build(inputEffect(0), operatingColorSpace()));
-    SkAutoTUnref<SkImageFilter> background(builder->build(inputEffect(1), operatingColorSpace()));
+    RefPtr<SkImageFilter> foreground(builder->build(inputEffect(0), operatingColorSpace()));
+    RefPtr<SkImageFilter> background(builder->build(inputEffect(1), operatingColorSpace()));
     SkAutoTUnref<SkXfermode> mode(SkXfermode::Create(toSkiaMode(m_mode)));
-    return new SkXfermodeImageFilter(mode, background, foreground);
+    return adoptRef(new SkXfermodeImageFilter(mode, background.get(), foreground.get()));
 }
 
 static TextStream& operator<<(TextStream& ts, const BlendModeType& type)
diff --git a/Source/core/platform/graphics/filters/FEBlend.h b/Source/core/platform/graphics/filters/FEBlend.h
index 1bac217..5185beb 100644
--- a/Source/core/platform/graphics/filters/FEBlend.h
+++ b/Source/core/platform/graphics/filters/FEBlend.h
@@ -49,7 +49,7 @@
                            unsigned colorArrayLength);
     void platformApplyNEON(unsigned char* srcPixelArrayA, unsigned char* srcPixelArrayB, unsigned char* dstPixelArray,
                            unsigned colorArrayLength);
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     virtual TextStream& externalRepresentation(TextStream&, int indention) const;
 
diff --git a/Source/core/platform/graphics/filters/FEColorMatrix.cpp b/Source/core/platform/graphics/filters/FEColorMatrix.cpp
index 2793882..9462e1c 100644
--- a/Source/core/platform/graphics/filters/FEColorMatrix.cpp
+++ b/Source/core/platform/graphics/filters/FEColorMatrix.cpp
@@ -281,11 +281,11 @@
     return true;
 }
 
-SkImageFilter* FEColorMatrix::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEColorMatrix::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
+    RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     SkAutoTUnref<SkColorFilter> filter(createColorFilter(m_type, m_values.data()));
-    return SkColorFilterImageFilter::Create(filter, input);
+    return adoptRef(SkColorFilterImageFilter::Create(filter, input.get()));
 }
 
 static TextStream& operator<<(TextStream& ts, const ColorMatrixType& type)
diff --git a/Source/core/platform/graphics/filters/FEColorMatrix.h b/Source/core/platform/graphics/filters/FEColorMatrix.h
index 1a86288..718817b 100644
--- a/Source/core/platform/graphics/filters/FEColorMatrix.h
+++ b/Source/core/platform/graphics/filters/FEColorMatrix.h
@@ -48,7 +48,7 @@
     const Vector<float>& values() const;
     bool setValues(const Vector<float>&);
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     virtual TextStream& externalRepresentation(TextStream&, int indention) const;
 
diff --git a/Source/core/platform/graphics/filters/FEComponentTransfer.cpp b/Source/core/platform/graphics/filters/FEComponentTransfer.cpp
index d766d0a..7eb2238 100644
--- a/Source/core/platform/graphics/filters/FEComponentTransfer.cpp
+++ b/Source/core/platform/graphics/filters/FEComponentTransfer.cpp
@@ -202,16 +202,16 @@
     return true;
 }
 
-SkImageFilter* FEComponentTransfer::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEComponentTransfer::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
+    RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
 
     unsigned char rValues[256], gValues[256], bValues[256], aValues[256];
     getValues(rValues, gValues, bValues, aValues);
 
     SkAutoTUnref<SkColorFilter> colorFilter(SkTableColorFilter::CreateARGB(aValues, rValues, gValues, bValues));
 
-    return SkColorFilterImageFilter::Create(colorFilter, input);
+    return adoptRef(SkColorFilterImageFilter::Create(colorFilter, input.get()));
 }
 
 void FEComponentTransfer::getValues(unsigned char rValues[256], unsigned char gValues[256], unsigned char bValues[256], unsigned char aValues[256])
diff --git a/Source/core/platform/graphics/filters/FEComponentTransfer.h b/Source/core/platform/graphics/filters/FEComponentTransfer.h
index 03c18c2..2b7d4cb 100644
--- a/Source/core/platform/graphics/filters/FEComponentTransfer.h
+++ b/Source/core/platform/graphics/filters/FEComponentTransfer.h
@@ -78,7 +78,7 @@
     ComponentTransferFunction alphaFunction() const;
     void setAlphaFunction(const ComponentTransferFunction&);
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     virtual TextStream& externalRepresentation(TextStream&, int indention) const;
 
diff --git a/Source/core/platform/graphics/filters/FEComposite.cpp b/Source/core/platform/graphics/filters/FEComposite.cpp
index 4dfeed4..209ae6e 100644
--- a/Source/core/platform/graphics/filters/FEComposite.cpp
+++ b/Source/core/platform/graphics/filters/FEComposite.cpp
@@ -392,15 +392,15 @@
     }
 }
 
-SkImageFilter* FEComposite::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEComposite::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> foreground(builder->build(inputEffect(0), operatingColorSpace()));
-    SkAutoTUnref<SkImageFilter> background(builder->build(inputEffect(1), operatingColorSpace()));
+    RefPtr<SkImageFilter> foreground(builder->build(inputEffect(0), operatingColorSpace()));
+    RefPtr<SkImageFilter> background(builder->build(inputEffect(1), operatingColorSpace()));
     if (m_type == FECOMPOSITE_OPERATOR_ARITHMETIC) {
         SkAutoTUnref<SkXfermode> mode(SkArithmeticMode::Create(SkFloatToScalar(m_k1), SkFloatToScalar(m_k2), SkFloatToScalar(m_k3), SkFloatToScalar(m_k4)));
-        return new SkXfermodeImageFilter(mode, background, foreground);
+        return adoptRef(new SkXfermodeImageFilter(mode, background.get(), foreground.get()));
     }
-    return new CompositeImageFilter(toXfermode(m_type), background, foreground);
+    return adoptRef(new CompositeImageFilter(toXfermode(m_type), background.get(), foreground.get()));
 }
 
 static TextStream& operator<<(TextStream& ts, const CompositeOperationType& type)
diff --git a/Source/core/platform/graphics/filters/FEComposite.h b/Source/core/platform/graphics/filters/FEComposite.h
index 4887329..cd364c3 100644
--- a/Source/core/platform/graphics/filters/FEComposite.h
+++ b/Source/core/platform/graphics/filters/FEComposite.h
@@ -65,7 +65,7 @@
 
     virtual TextStream& externalRepresentation(TextStream&, int indention) const;
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
 protected:
     virtual bool requiresValidPreMultipliedPixels() OVERRIDE { return m_type != FECOMPOSITE_OPERATOR_ARITHMETIC; }
diff --git a/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp b/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
index e516f40..2753555 100644
--- a/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
+++ b/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
@@ -516,9 +516,9 @@
 
 namespace WebCore {
 
-SkImageFilter* FEConvolveMatrix::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEConvolveMatrix::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
+    RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
 
     SkISize kernelSize(SkISize::Make(m_kernelSize.width(), m_kernelSize.height()));
     int numElements = kernelSize.width() * kernelSize.height();
@@ -530,7 +530,7 @@
     OwnArrayPtr<SkScalar> kernel = adoptArrayPtr(new SkScalar[numElements]);
     for (int i = 0; i < numElements; ++i)
         kernel[i] = SkFloatToScalar(m_kernelMatrix[numElements - 1 - i]);
-    return new SkMatrixConvolutionImageFilter(kernelSize, kernel.get(), gain, bias, target, tileMode, convolveAlpha, input);
+    return adoptRef(new SkMatrixConvolutionImageFilter(kernelSize, kernel.get(), gain, bias, target, tileMode, convolveAlpha, input.get()));
 }
 
 static TextStream& operator<<(TextStream& ts, const EdgeModeType& type)
diff --git a/Source/core/platform/graphics/filters/FEConvolveMatrix.h b/Source/core/platform/graphics/filters/FEConvolveMatrix.h
index 4f8915e..d9f0ca6 100644
--- a/Source/core/platform/graphics/filters/FEConvolveMatrix.h
+++ b/Source/core/platform/graphics/filters/FEConvolveMatrix.h
@@ -69,7 +69,7 @@
     bool preserveAlpha() const;
     bool setPreserveAlpha(bool);
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
 
diff --git a/Source/core/platform/graphics/filters/FEDisplacementMap.cpp b/Source/core/platform/graphics/filters/FEDisplacementMap.cpp
index abb22c1..67853d8 100644
--- a/Source/core/platform/graphics/filters/FEDisplacementMap.cpp
+++ b/Source/core/platform/graphics/filters/FEDisplacementMap.cpp
@@ -215,15 +215,15 @@
     return true;
 }
 
-SkImageFilter* FEDisplacementMap::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEDisplacementMap::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkImageFilter* color = builder->build(inputEffect(0), operatingColorSpace());
-    SkImageFilter* displ = builder->build(inputEffect(1), operatingColorSpace());
+    RefPtr<SkImageFilter> color = builder->build(inputEffect(0), operatingColorSpace());
+    RefPtr<SkImageFilter> displ = builder->build(inputEffect(1), operatingColorSpace());
     SkDisplacementMapEffect::ChannelSelectorType typeX = toSkiaMode(m_xChannelSelector);
     SkDisplacementMapEffect::ChannelSelectorType typeY = toSkiaMode(m_yChannelSelector);
     // FIXME : Only applyHorizontalScale is used and applyVerticalScale is ignored
     // This can be fixed by adding a 2nd scale parameter to SkDisplacementMapEffect
-    return new SkDisplacementMapEffect(typeX, typeY, SkFloatToScalar(filter()->applyHorizontalScale(m_scale)), displ, color);
+    return adoptRef(new SkDisplacementMapEffect(typeX, typeY, SkFloatToScalar(filter()->applyHorizontalScale(m_scale)), displ.get(), color.get()));
 }
 
 static TextStream& operator<<(TextStream& ts, const ChannelSelectorType& type)
diff --git a/Source/core/platform/graphics/filters/FEDisplacementMap.h b/Source/core/platform/graphics/filters/FEDisplacementMap.h
index 0d914f7..3ac54a1 100644
--- a/Source/core/platform/graphics/filters/FEDisplacementMap.h
+++ b/Source/core/platform/graphics/filters/FEDisplacementMap.h
@@ -63,7 +63,7 @@
     virtual void applySoftware() OVERRIDE;
     virtual bool applySkia() OVERRIDE;
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     ChannelSelectorType m_xChannelSelector;
     ChannelSelectorType m_yChannelSelector;
diff --git a/Source/core/platform/graphics/filters/FEFlood.cpp b/Source/core/platform/graphics/filters/FEFlood.cpp
index 4b85b44..19301bf 100644
--- a/Source/core/platform/graphics/filters/FEFlood.cpp
+++ b/Source/core/platform/graphics/filters/FEFlood.cpp
@@ -125,10 +125,10 @@
     resultImage->context()->fillRect(FloatRect(FloatPoint(), absolutePaintRect().size()), color);
 }
 
-SkImageFilter* FEFlood::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEFlood::createImageFilter(SkiaImageFilterBuilder* builder)
 {
     Color color = colorWithOverrideAlpha(floodColor().rgb(), floodOpacity());
-    return new FloodImageFilter(color.rgb());
+    return adoptRef(new FloodImageFilter(color.rgb()));
 }
 
 TextStream& FEFlood::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FEFlood.h b/Source/core/platform/graphics/filters/FEFlood.h
index 640ca52..633fc98 100644
--- a/Source/core/platform/graphics/filters/FEFlood.h
+++ b/Source/core/platform/graphics/filters/FEFlood.h
@@ -44,7 +44,7 @@
     void setOperatingColorSpace(ColorSpace) OVERRIDE { }
     void setResultColorSpace(ColorSpace) OVERRIDE { }
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
 
diff --git a/Source/core/platform/graphics/filters/FEGaussianBlur.cpp b/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
index d622b80..0a8d60b 100644
--- a/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
+++ b/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
@@ -338,12 +338,12 @@
     return true;
 }
 
-SkImageFilter* FEGaussianBlur::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEGaussianBlur::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
+    RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     float stdX = filter()->applyHorizontalScale(m_stdX);
     float stdY = filter()->applyVerticalScale(m_stdY);
-    return new SkBlurImageFilter(SkFloatToScalar(stdX), SkFloatToScalar(stdY), input);
+    return adoptRef(new SkBlurImageFilter(SkFloatToScalar(stdX), SkFloatToScalar(stdY), input.get()));
 }
 
 TextStream& FEGaussianBlur::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FEGaussianBlur.h b/Source/core/platform/graphics/filters/FEGaussianBlur.h
index 1b9b723..ed26fe8 100644
--- a/Source/core/platform/graphics/filters/FEGaussianBlur.h
+++ b/Source/core/platform/graphics/filters/FEGaussianBlur.h
@@ -74,7 +74,7 @@
     inline void platformApply(Uint8ClampedArray* srcPixelArray, Uint8ClampedArray* tmpPixelArray, unsigned kernelSizeX, unsigned kernelSizeY, IntSize& paintSize);
 
     inline void platformApplyGeneric(Uint8ClampedArray* srcPixelArray, Uint8ClampedArray* tmpPixelArray, unsigned kernelSizeX, unsigned kernelSizeY, IntSize& paintSize);
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     float m_stdX;
     float m_stdY;
diff --git a/Source/core/platform/graphics/filters/FELighting.cpp b/Source/core/platform/graphics/filters/FELighting.cpp
index 3f43262..cfe5880 100644
--- a/Source/core/platform/graphics/filters/FELighting.cpp
+++ b/Source/core/platform/graphics/filters/FELighting.cpp
@@ -414,9 +414,9 @@
     drawLighting(srcPixelArray, absolutePaintSize.width(), absolutePaintSize.height());
 }
 
-SkImageFilter* FELighting::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FELighting::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> input(builder ? builder->build(inputEffect(0), operatingColorSpace()) : 0);
+    RefPtr<SkImageFilter> input(builder ? builder->build(inputEffect(0), operatingColorSpace()) : 0);
     switch (m_lightSource->type()) {
     case LS_DISTANT: {
         DistantLightSource* distantLightSource = static_cast<DistantLightSource*>(m_lightSource.get());
@@ -426,18 +426,18 @@
                            sinf(azimuthRad) * cosf(elevationRad),
                            sinf(elevationRad));
         if (m_specularConstant > 0)
-            return SkLightingImageFilter::CreateDistantLitSpecular(direction, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input);
+            return adoptRef(SkLightingImageFilter::CreateDistantLitSpecular(direction, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get()));
         else
-            return SkLightingImageFilter::CreateDistantLitDiffuse(direction, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input);
+            return adoptRef(SkLightingImageFilter::CreateDistantLitDiffuse(direction, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get()));
     }
     case LS_POINT: {
         PointLightSource* pointLightSource = static_cast<PointLightSource*>(m_lightSource.get());
         FloatPoint3D position = pointLightSource->position();
         SkPoint3 skPosition(position.x(), position.y(), position.z());
         if (m_specularConstant > 0)
-            return SkLightingImageFilter::CreatePointLitSpecular(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input);
+            return adoptRef(SkLightingImageFilter::CreatePointLitSpecular(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get()));
         else
-            return SkLightingImageFilter::CreatePointLitDiffuse(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input);
+            return adoptRef(SkLightingImageFilter::CreatePointLitDiffuse(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get()));
     }
     case LS_SPOT: {
         SpotLightSource* spotLightSource = static_cast<SpotLightSource*>(m_lightSource.get());
@@ -448,9 +448,9 @@
         if (!limitingConeAngle || limitingConeAngle > 90 || limitingConeAngle < -90)
             limitingConeAngle = 90;
         if (m_specularConstant > 0)
-            return SkLightingImageFilter::CreateSpotLitSpecular(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input);
+            return adoptRef(SkLightingImageFilter::CreateSpotLitSpecular(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get()));
         else
-            return SkLightingImageFilter::CreateSpotLitDiffuse(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input);
+            return adoptRef(SkLightingImageFilter::CreateSpotLitDiffuse(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get()));
     }
     default:
         ASSERT_NOT_REACHED();
@@ -482,7 +482,8 @@
     GraphicsContext* dstContext = resultImage->context();
 
     SkPaint paint;
-    paint.setImageFilter(createImageFilter(0))->unref();
+    RefPtr<SkImageFilter> filter = createImageFilter(0);
+    paint.setImageFilter(filter.get());
     dstContext->drawBitmap(nativeImage->bitmap(), drawingRegion.location().x(), drawingRegion.location().y(), &paint);
     return true;
 }
diff --git a/Source/core/platform/graphics/filters/FELighting.h b/Source/core/platform/graphics/filters/FELighting.h
index 6974d14..de73e83 100644
--- a/Source/core/platform/graphics/filters/FELighting.h
+++ b/Source/core/platform/graphics/filters/FELighting.h
@@ -44,7 +44,7 @@
 
 class FELighting : public FilterEffect {
 public:
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
 
diff --git a/Source/core/platform/graphics/filters/FEMerge.cpp b/Source/core/platform/graphics/filters/FEMerge.cpp
index f1e43a1..2dd3bbf 100644
--- a/Source/core/platform/graphics/filters/FEMerge.cpp
+++ b/Source/core/platform/graphics/filters/FEMerge.cpp
@@ -60,17 +60,17 @@
     }
 }
 
-SkImageFilter* FEMerge::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEMerge::createImageFilter(SkiaImageFilterBuilder* builder)
 {
     unsigned size = numberOfEffectInputs();
 
-    OwnArrayPtr<SkAutoTUnref<SkImageFilter> > inputRefs = adoptArrayPtr(new SkAutoTUnref<SkImageFilter>[size]);
+    OwnArrayPtr<RefPtr<SkImageFilter> > inputRefs = adoptArrayPtr(new RefPtr<SkImageFilter>[size]);
     OwnArrayPtr<SkImageFilter*> inputs = adoptArrayPtr(new SkImageFilter*[size]);
     for (unsigned i = 0; i < size; ++i) {
-        inputRefs[i].reset(builder->build(inputEffect(i), operatingColorSpace()));
+        inputRefs[i] = builder->build(inputEffect(i), operatingColorSpace());
         inputs[i] = inputRefs[i].get();
     }
-    return new SkMergeImageFilter(inputs.get(), size);
+    return adoptRef(new SkMergeImageFilter(inputs.get(), size));
 }
 
 TextStream& FEMerge::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FEMerge.h b/Source/core/platform/graphics/filters/FEMerge.h
index 20b0c4a..83f37c7 100644
--- a/Source/core/platform/graphics/filters/FEMerge.h
+++ b/Source/core/platform/graphics/filters/FEMerge.h
@@ -33,7 +33,7 @@
 public:
     static PassRefPtr<FEMerge> create(Filter*);
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     virtual TextStream& externalRepresentation(TextStream&, int indention) const;
 
diff --git a/Source/core/platform/graphics/filters/FEMorphology.cpp b/Source/core/platform/graphics/filters/FEMorphology.cpp
index c2a4b2d..5ccbe69 100644
--- a/Source/core/platform/graphics/filters/FEMorphology.cpp
+++ b/Source/core/platform/graphics/filters/FEMorphology.cpp
@@ -267,14 +267,14 @@
     return true;
 }
 
-SkImageFilter* FEMorphology::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEMorphology::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
+    RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     SkScalar radiusX = SkFloatToScalar(filter()->applyHorizontalScale(m_radiusX));
     SkScalar radiusY = SkFloatToScalar(filter()->applyVerticalScale(m_radiusY));
     if (m_type == FEMORPHOLOGY_OPERATOR_DILATE)
-        return new SkDilateImageFilter(radiusX, radiusY, input);
-    return new SkErodeImageFilter(radiusX, radiusY, input);
+        return adoptRef(new SkDilateImageFilter(radiusX, radiusY, input.get()));
+    return adoptRef(new SkErodeImageFilter(radiusX, radiusY, input.get()));
 }
 
 static TextStream& operator<<(TextStream& ts, const MorphologyOperatorType& type)
diff --git a/Source/core/platform/graphics/filters/FEMorphology.h b/Source/core/platform/graphics/filters/FEMorphology.h
index 5ab36cd..8a9a57a 100644
--- a/Source/core/platform/graphics/filters/FEMorphology.h
+++ b/Source/core/platform/graphics/filters/FEMorphology.h
@@ -46,7 +46,7 @@
     float radiusY() const;
     bool setRadiusY(float);
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     virtual void determineAbsolutePaintRect();
     virtual FloatRect mapRect(const FloatRect&, bool forward = true) OVERRIDE FINAL;
diff --git a/Source/core/platform/graphics/filters/FEOffset.cpp b/Source/core/platform/graphics/filters/FEOffset.cpp
index 9c41ced..132ee9e 100644
--- a/Source/core/platform/graphics/filters/FEOffset.cpp
+++ b/Source/core/platform/graphics/filters/FEOffset.cpp
@@ -152,11 +152,11 @@
     resultImage->context()->drawImageBuffer(in->asImageBuffer(), drawingRegion);
 }
 
-SkImageFilter* FEOffset::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEOffset::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
+    RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     Filter* filter = this->filter();
-    return new OffsetImageFilter(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), input);
+    return adoptRef(new OffsetImageFilter(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), input.get()));
 }
 
 TextStream& FEOffset::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FEOffset.h b/Source/core/platform/graphics/filters/FEOffset.h
index daa210f..31f08cc 100644
--- a/Source/core/platform/graphics/filters/FEOffset.h
+++ b/Source/core/platform/graphics/filters/FEOffset.h
@@ -43,7 +43,7 @@
 
     virtual TextStream& externalRepresentation(TextStream&, int indention) const;
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
 private:
     FEOffset(Filter*, float dx, float dy);
diff --git a/Source/core/platform/graphics/filters/FETile.cpp b/Source/core/platform/graphics/filters/FETile.cpp
index 6ceb85b..f7fac7f 100644
--- a/Source/core/platform/graphics/filters/FETile.cpp
+++ b/Source/core/platform/graphics/filters/FETile.cpp
@@ -151,11 +151,11 @@
     filterContext->fillRect(FloatRect(FloatPoint(), absolutePaintRect().size()));
 }
 
-SkImageFilter* FETile::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FETile::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
+    RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     FloatRect srcRect = inputEffect(0) ? inputEffect(0)->effectBoundaries() : FloatRect();
-    return new TileImageFilter(srcRect, effectBoundaries(), input);
+    return adoptRef(new TileImageFilter(srcRect, effectBoundaries(), input.get()));
 }
 
 TextStream& FETile::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FETile.h b/Source/core/platform/graphics/filters/FETile.h
index d1a3e11..6f697ef 100644
--- a/Source/core/platform/graphics/filters/FETile.h
+++ b/Source/core/platform/graphics/filters/FETile.h
@@ -32,7 +32,7 @@
 public:
     static PassRefPtr<FETile> create(Filter* filter);
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
     virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
 
diff --git a/Source/core/platform/graphics/filters/FETurbulence.cpp b/Source/core/platform/graphics/filters/FETurbulence.cpp
index 3ca5dc6..29e0779 100644
--- a/Source/core/platform/graphics/filters/FETurbulence.cpp
+++ b/Source/core/platform/graphics/filters/FETurbulence.cpp
@@ -437,9 +437,10 @@
     return true;
 }
 
-SkImageFilter* FETurbulence::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FETurbulence::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    return SkRectShaderImageFilter::Create(createShader(IntRect()), SkRect());
+    SkAutoTUnref<SkShader> shader(createShader(IntRect()));
+    return adoptRef(SkRectShaderImageFilter::Create(shader, SkRect()));
 }
 
 static TextStream& operator<<(TextStream& ts, const TurbulenceType& type)
diff --git a/Source/core/platform/graphics/filters/FETurbulence.h b/Source/core/platform/graphics/filters/FETurbulence.h
index c757c01..a294666 100644
--- a/Source/core/platform/graphics/filters/FETurbulence.h
+++ b/Source/core/platform/graphics/filters/FETurbulence.h
@@ -119,7 +119,7 @@
 
     virtual void applySoftware() OVERRIDE;
     virtual bool applySkia() OVERRIDE;
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
     SkShader* createShader(const IntRect& filterRegion);
 
     inline void initPaint(PaintingData&);
diff --git a/Source/core/platform/graphics/filters/FilterEffect.cpp b/Source/core/platform/graphics/filters/FilterEffect.cpp
index 144f000..01e4b0a 100644
--- a/Source/core/platform/graphics/filters/FilterEffect.cpp
+++ b/Source/core/platform/graphics/filters/FilterEffect.cpp
@@ -27,6 +27,7 @@
 
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/platform/graphics/filters/Filter.h"
+#include "third_party/skia/include/core/SkImageFilter.h"
 #include "wtf/Uint8ClampedArray.h"
 
 #if HAVE(ARM_NEON_INTRINSICS)
@@ -475,4 +476,9 @@
     return subregion;
 }
 
+PassRefPtr<SkImageFilter> FilterEffect::createImageFilter(SkiaImageFilterBuilder* builder)
+{
+    return 0;
+}
+
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/filters/FilterEffect.h b/Source/core/platform/graphics/filters/FilterEffect.h
index 46230ea..8353bf6 100644
--- a/Source/core/platform/graphics/filters/FilterEffect.h
+++ b/Source/core/platform/graphics/filters/FilterEffect.h
@@ -100,7 +100,7 @@
     // Only the arithmetic composite filter ever needs to perform correction.
     virtual void correctFilterResultIfNeeded() { }
 
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*) { return 0; }
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*);
 
     virtual void determineAbsolutePaintRect();
 
diff --git a/Source/core/platform/graphics/filters/FilterOperation.h b/Source/core/platform/graphics/filters/FilterOperation.h
index b90b04d..3473418 100644
--- a/Source/core/platform/graphics/filters/FilterOperation.h
+++ b/Source/core/platform/graphics/filters/FilterOperation.h
@@ -26,12 +26,10 @@
 #ifndef FilterOperation_h
 #define FilterOperation_h
 
-#include "core/loader/cache/CachedSVGDocumentReference.h"
+#include "core/loader/cache/DocumentResourceReference.h"
 #include "core/platform/Length.h"
 #include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/LayoutSize.h"
 #include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
 #include "core/platform/graphics/filters/ReferenceFilter.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
@@ -74,13 +72,6 @@
 
     virtual PassRefPtr<FilterOperation> blend(const FilterOperation* /*from*/, double /*progress*/, bool /*blendToPassthrough*/ = false)
     {
-        ASSERT(!blendingNeedsRendererSize());
-        return 0;
-    }
-
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* /*from*/, double /*progress*/, const LayoutSize&, bool /*blendToPassthrough*/ = false)
-    {
-        ASSERT(blendingNeedsRendererSize());
         return 0;
     }
 
@@ -93,8 +84,6 @@
     virtual bool affectsOpacity() const { return false; }
     // True if the the value of one pixel can affect the value of another pixel under this operation, such as blur.
     virtual bool movesPixels() const { return false; }
-    // True if the filter needs the size of the box in order to calculate the animations.
-    virtual bool blendingNeedsRendererSize() const { return false; }
 
 protected:
     FilterOperation(OperationType type)
@@ -160,8 +149,8 @@
     const String& url() const { return m_url; }
     const String& fragment() const { return m_fragment; }
 
-    CachedSVGDocumentReference* cachedSVGDocumentReference() const { return m_cachedSVGDocumentReference.get(); }
-    void setCachedSVGDocumentReference(PassOwnPtr<CachedSVGDocumentReference> cachedSVGDocumentReference) { m_cachedSVGDocumentReference = cachedSVGDocumentReference; }
+    DocumentResourceReference* documentResourceReference() const { return m_documentResourceReference.get(); }
+    void setDocumentResourceReference(PassOwnPtr<DocumentResourceReference> documentResourceReference) { m_documentResourceReference = documentResourceReference; }
 
     ReferenceFilter* filter() const { return m_filter.get(); }
     void setFilter(PassRefPtr<ReferenceFilter> filter) { m_filter = filter; }
@@ -185,7 +174,7 @@
 
     String m_url;
     String m_fragment;
-    OwnPtr<CachedSVGDocumentReference> m_cachedSVGDocumentReference;
+    OwnPtr<DocumentResourceReference> m_documentResourceReference;
     RefPtr<ReferenceFilter> m_filter;
 };
 
diff --git a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
index 2b30900..9e5bc76 100644
--- a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
+++ b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
@@ -29,9 +29,9 @@
 #include "SkBlurImageFilter.h"
 #include "SkColorFilterImageFilter.h"
 #include "SkColorMatrixFilter.h"
+#include "SkDropShadowImageFilter.h"
 #include "SkTableColorFilter.h"
 #include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/filters/DropShadowImageFilter.h"
 #include "core/platform/graphics/filters/FilterEffect.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
 #include "core/platform/graphics/filters/SourceGraphic.h"
@@ -153,10 +153,10 @@
     matrix[18] = 1;
 }
 
-SkImageFilter* createMatrixImageFilter(SkScalar matrix[20], SkImageFilter* input)
+PassRefPtr<SkImageFilter> createMatrixImageFilter(SkScalar matrix[20], SkImageFilter* input)
 {
-    SkAutoTUnref<SkColorFilter> colorFilter(new SkColorMatrixFilter(matrix));
-    return SkColorFilterImageFilter::Create(colorFilter, input);
+    RefPtr<SkColorFilter> colorFilter(adoptRef(new SkColorMatrixFilter(matrix)));
+    return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), input));
 }
 
 };
@@ -169,31 +169,27 @@
 
 SkiaImageFilterBuilder::~SkiaImageFilterBuilder()
 {
-    for (FilterBuilderHashMap::iterator it = m_map.begin(); it != m_map.end(); ++it)
-        SkSafeUnref(it->value);
 }
 
-SkImageFilter* SkiaImageFilterBuilder::build(FilterEffect* effect, ColorSpace colorSpace)
+PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::build(FilterEffect* effect, ColorSpace colorSpace)
 {
     if (!effect)
         return 0;
 
-    SkImageFilter* filter = 0;
     FilterColorSpacePair key(effect, colorSpace);
     FilterBuilderHashMap::iterator it = m_map.find(key);
     if (it != m_map.end()) {
-        filter = it->value;
+        return it->value;
     } else {
         // Note that we may still need the color transform even if the filter is null
-        filter = transformColorSpace(effect->createImageFilter(this), effect->operatingColorSpace(), colorSpace);
+        RefPtr<SkImageFilter> origFilter = effect->createImageFilter(this);
+        RefPtr<SkImageFilter> filter = transformColorSpace(origFilter.get(), effect->operatingColorSpace(), colorSpace);
         m_map.set(key, filter);
+        return filter.release();
     }
-    // The hash map has a ref, so we return a new ref for the caller.
-    SkSafeRef(filter);
-    return filter;
 }
 
-SkImageFilter* SkiaImageFilterBuilder::transformColorSpace(
+PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::transformColorSpace(
     SkImageFilter* input, ColorSpace srcColorSpace, ColorSpace dstColorSpace) {
     if ((srcColorSpace == dstColorSpace)
         || (srcColorSpace != ColorSpaceLinearRGB && srcColorSpace != ColorSpaceDeviceRGB)
@@ -205,14 +201,16 @@
         lut = &ImageBuffer::getLinearRgbLUT()[0];
     else if (dstColorSpace == ColorSpaceDeviceRGB)
         lut = &ImageBuffer::getDeviceRgbLUT()[0];
+    else
+        return input;
 
-    return lut ? SkColorFilterImageFilter::Create(
-        SkTableColorFilter::CreateARGB(0, lut, lut, lut), input) : input;
+    RefPtr<SkColorFilter> colorFilter(adoptRef(SkTableColorFilter::CreateARGB(0, lut, lut, lut)));
+    return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), input));
 }
 
-SkImageFilter* SkiaImageFilterBuilder::build(const FilterOperations& operations)
+PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::build(const FilterOperations& operations)
 {
-    SkAutoTUnref<SkImageFilter> filter;
+    RefPtr<SkImageFilter> filter;
     SkScalar matrix[20];
     ColorSpace currentColorSpace = ColorSpaceDeviceRGB;
     for (size_t i = 0; i < operations.size(); ++i) {
@@ -228,11 +226,11 @@
                 // (Only one of these will actually have a color transform on it.)
                 FilterColorSpacePair deviceKey(referenceFilter->sourceGraphic(), ColorSpaceDeviceRGB);
                 FilterColorSpacePair linearKey(referenceFilter->sourceGraphic(), ColorSpaceLinearRGB);
-                m_map.set(deviceKey, transformColorSpace(filter, currentColorSpace, ColorSpaceDeviceRGB));
-                m_map.set(linearKey, transformColorSpace(filter, currentColorSpace, ColorSpaceLinearRGB));
+                m_map.set(deviceKey, transformColorSpace(filter.get(), currentColorSpace, ColorSpaceDeviceRGB));
+                m_map.set(linearKey, transformColorSpace(filter.get(), currentColorSpace, ColorSpaceLinearRGB));
 
                 currentColorSpace = filterEffect->operatingColorSpace();
-                filter.reset(SkiaImageFilterBuilder::build(filterEffect, currentColorSpace));
+                filter = SkiaImageFilterBuilder::build(filterEffect, currentColorSpace);
                 // We might have no reference to the SourceGraphic's Skia filter now, so make
                 // sure we don't keep it in the map anymore.
                 m_map.remove(deviceKey);
@@ -243,59 +241,59 @@
         case FilterOperation::GRAYSCALE: {
             float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
             getGrayscaleMatrix(1 - amount, matrix);
-            filter.reset(createMatrixImageFilter(matrix, filter));
+            filter = createMatrixImageFilter(matrix, filter.get());
             break;
         }
         case FilterOperation::SEPIA: {
             float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
             getSepiaMatrix(1 - amount, matrix);
-            filter.reset(createMatrixImageFilter(matrix, filter));
+            filter = createMatrixImageFilter(matrix, filter.get());
             break;
         }
         case FilterOperation::SATURATE: {
             float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
             getSaturateMatrix(amount, matrix);
-            filter.reset(createMatrixImageFilter(matrix, filter));
+            filter = createMatrixImageFilter(matrix, filter.get());
             break;
         }
         case FilterOperation::HUE_ROTATE: {
             float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
             getHueRotateMatrix(amount, matrix);
-            filter.reset(createMatrixImageFilter(matrix, filter));
+            filter = createMatrixImageFilter(matrix, filter.get());
             break;
         }
         case FilterOperation::INVERT: {
             float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
             getInvertMatrix(amount, matrix);
-            filter.reset(createMatrixImageFilter(matrix, filter));
+            filter = createMatrixImageFilter(matrix, filter.get());
             break;
         }
         case FilterOperation::OPACITY: {
             float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
             getOpacityMatrix(amount, matrix);
-            filter.reset(createMatrixImageFilter(matrix, filter));
+            filter = createMatrixImageFilter(matrix, filter.get());
             break;
         }
         case FilterOperation::BRIGHTNESS: {
             float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
             getBrightnessMatrix(amount, matrix);
-            filter.reset(createMatrixImageFilter(matrix, filter));
+            filter = createMatrixImageFilter(matrix, filter.get());
             break;
         }
         case FilterOperation::CONTRAST: {
             float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
             getContrastMatrix(amount, matrix);
-            filter.reset(createMatrixImageFilter(matrix, filter));
+            filter = createMatrixImageFilter(matrix, filter.get());
             break;
         }
         case FilterOperation::BLUR: {
             float pixelRadius = static_cast<const BlurFilterOperation*>(&op)->stdDeviation().getFloatValue();
-            filter.reset(new SkBlurImageFilter(pixelRadius, pixelRadius, filter));
+            filter = adoptRef(new SkBlurImageFilter(pixelRadius, pixelRadius, filter.get()));
             break;
         }
         case FilterOperation::DROP_SHADOW: {
             const DropShadowFilterOperation* drop = static_cast<const DropShadowFilterOperation*>(&op);
-            filter.reset(new DropShadowImageFilter(SkIntToScalar(drop->x()), SkIntToScalar(drop->y()), SkIntToScalar(drop->stdDeviation()), drop->color().rgb(), filter));
+            filter = adoptRef(new SkDropShadowImageFilter(SkIntToScalar(drop->x()), SkIntToScalar(drop->y()), SkIntToScalar(drop->stdDeviation()), drop->color().rgb(), filter.get()));
             break;
         }
         case FilterOperation::VALIDATED_CUSTOM:
@@ -308,9 +306,9 @@
     }
     if (currentColorSpace != ColorSpaceDeviceRGB) {
         // Transform to device color space at the end of processing, if required
-        filter.reset(transformColorSpace(filter.get(), currentColorSpace, ColorSpaceDeviceRGB));
+        filter = transformColorSpace(filter.get(), currentColorSpace, ColorSpaceDeviceRGB);
     }
-    return filter.detach();
+    return filter.release();
 }
 
 };
diff --git a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
index aa90df3..8409396 100644
--- a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
+++ b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
@@ -40,14 +40,14 @@
     SkiaImageFilterBuilder();
     ~SkiaImageFilterBuilder();
 
-    SkImageFilter* build(FilterEffect*, ColorSpace);
-    SkImageFilter* build(const FilterOperations&);
+    PassRefPtr<SkImageFilter> build(FilterEffect*, ColorSpace);
+    PassRefPtr<SkImageFilter> build(const FilterOperations&);
 
-    SkImageFilter* transformColorSpace(
+    PassRefPtr<SkImageFilter> transformColorSpace(
         SkImageFilter* input, ColorSpace srcColorSpace, ColorSpace dstColorSpace);
 private:
     typedef std::pair<FilterEffect*, ColorSpace> FilterColorSpacePair;
-    typedef HashMap<FilterColorSpacePair, SkImageFilter*> FilterBuilderHashMap;
+    typedef HashMap<FilterColorSpacePair, RefPtr<SkImageFilter> > FilterBuilderHashMap;
     FilterBuilderHashMap m_map;
 };
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterArrayParameter.h b/Source/core/platform/graphics/filters/custom/CustomFilterArrayParameter.h
index ae1fe46..ccaaf20 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterArrayParameter.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterArrayParameter.h
@@ -48,7 +48,7 @@
 
     void addValue(double value) { m_data.append(value); }
 
-    virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* from, double progress, const LayoutSize&)
+    virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* from, double progress)
     {
         if (!from || !isSameType(*from))
             return this;
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterNumberParameter.h b/Source/core/platform/graphics/filters/custom/CustomFilterNumberParameter.h
index 9706639..b263495 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterNumberParameter.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterNumberParameter.h
@@ -48,7 +48,7 @@
 
     void addValue(double value) { m_data.append(value); }
 
-    virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* from, double progress, const LayoutSize&)
+    virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* from, double progress)
     {
         if (!from || !isSameType(*from))
             return this;
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
index 0ee1bf0..99aa9db 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
@@ -53,7 +53,7 @@
 {
 }
 
-PassRefPtr<FilterOperation> CustomFilterOperation::blend(const FilterOperation* from, double progress, const LayoutSize& size, bool blendToPassthrough)
+PassRefPtr<FilterOperation> CustomFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
 {
     // FIXME: There's no way to decide what is the "passthrough filter" for shaders using the current CSS Syntax.
     // https://bugs.webkit.org/show_bug.cgi?id=84903
@@ -69,7 +69,7 @@
         return this;
 
     CustomFilterParameterList animatedParameters;
-    m_parameters.blend(fromOp->m_parameters, progress, size, animatedParameters);
+    m_parameters.blend(fromOp->m_parameters, progress, animatedParameters);
     return CustomFilterOperation::create(m_program, animatedParameters, m_meshRows, m_meshColumns, m_meshType);
 }
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
index 3210267..1ef7d70 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
@@ -61,9 +61,8 @@
 
     virtual bool affectsOpacity() const { return true; }
     virtual bool movesPixels() const { return true; }
-    virtual bool blendingNeedsRendererSize() const { return true; }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, const LayoutSize&, bool blendToPassthrough = false);
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
 
 protected:
     CustomFilterOperation(PassRefPtr<CustomFilterProgram>, const CustomFilterParameterList&, unsigned meshRows, unsigned meshColumns, CustomFilterMeshType);
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterParameter.h b/Source/core/platform/graphics/filters/custom/CustomFilterParameter.h
index 57c2a55..dd468f1 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterParameter.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterParameter.h
@@ -56,7 +56,7 @@
 
     bool isSameType(const CustomFilterParameter& other) const { return parameterType() == other.parameterType(); }
 
-    virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter*, double progress, const LayoutSize&) = 0;
+    virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter*, double progress) = 0;
     virtual bool operator==(const CustomFilterParameter&) const = 0;
     bool operator!=(const CustomFilterParameter& o) const { return !(*this == o); }
 protected:
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.cpp
index c526d36..bc3e404 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.cpp
@@ -68,7 +68,7 @@
 }
 
 void CustomFilterParameterList::blend(const CustomFilterParameterList& fromList,
-    double progress, const LayoutSize& frameSize, CustomFilterParameterList& resultList) const
+    double progress, CustomFilterParameterList& resultList) const
 {
     // This method expects both lists to be sorted by parameter name and the result list is also sorted.
     ASSERT(checkAlphabeticalOrder());
@@ -78,7 +78,7 @@
         CustomFilterParameter* paramFrom = fromList.at(fromListIndex).get();
         CustomFilterParameter* paramTo = at(toListIndex).get();
         if (paramFrom->name() == paramTo->name()) {
-            resultList.append(paramTo->blend(paramFrom, progress, frameSize));
+            resultList.append(paramTo->blend(paramFrom, progress));
             ++fromListIndex;
             ++toListIndex;
             continue;
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.h b/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.h
index 6db3e99..f9e7270 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.h
@@ -44,7 +44,7 @@
     explicit CustomFilterParameterList(size_t);
 
     bool checkAlphabeticalOrder() const;
-    void blend(const CustomFilterParameterList& from, double progress, const LayoutSize&, CustomFilterParameterList& resultList) const;
+    void blend(const CustomFilterParameterList& from, double progress, CustomFilterParameterList& resultList) const;
     bool operator==(const CustomFilterParameterList&) const;
 };
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h b/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
index 0b216b0..71abf75 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
@@ -46,7 +46,7 @@
         return adoptRef(new CustomFilterTransformParameter(name));
     }
 
-    virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* fromParameter, double progress, const LayoutSize& size)
+    virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* fromParameter, double progress)
     {
         if (!fromParameter || !isSameType(*fromParameter))
             return this;
@@ -59,7 +59,7 @@
 
         RefPtr<CustomFilterTransformParameter> result = CustomFilterTransformParameter::create(name());
         if (from.size() && to.size())
-            result->setOperations(to.blend(from, progress, size));
+            result->setOperations(to.blend(from, progress));
         else
             result->setOperations(progress > 0.5 ? to : from);
         return result;
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp
index 02076ea..35aa68e 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp
@@ -133,7 +133,7 @@
 
 String CustomFilterValidatedProgram::defaultVertexShaderString()
 {
-    DEFINE_STATIC_LOCAL(String, vertexShaderString, (ASCIILiteral(SHADER(
+    DEFINE_STATIC_LOCAL(String, vertexShaderString, (SHADER(
         attribute mediump vec4 a_position;
         uniform mediump mat4 u_projectionMatrix;
 
@@ -141,17 +141,17 @@
         {
             gl_Position = u_projectionMatrix * a_position;
         }
-    ))));
+    )));
     return vertexShaderString;
 }
 
 String CustomFilterValidatedProgram::defaultFragmentShaderString()
 {
-    DEFINE_STATIC_LOCAL(String, fragmentShaderString, (ASCIILiteral(SHADER(
+    DEFINE_STATIC_LOCAL(String, fragmentShaderString, (SHADER(
         void main()
         {
         }
-    ))));
+    )));
     return fragmentShaderString;
 }
 
diff --git a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp
index 37cc3d1..c285947 100644
--- a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp
+++ b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp
@@ -31,7 +31,6 @@
 
 #include "core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h"
 
-#include "core/platform/graphics/LayoutSize.h"
 #include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
 #include "core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
 #include "wtf/UnusedParam.h"
@@ -53,10 +52,9 @@
 {
 }
 
-PassRefPtr<FilterOperation> ValidatedCustomFilterOperation::blend(const FilterOperation*, double progress, const LayoutSize& size, bool blendToPassthrough)
+PassRefPtr<FilterOperation> ValidatedCustomFilterOperation::blend(const FilterOperation*, double progress, bool blendToPassthrough)
 {
     UNUSED_PARAM(progress);
-    UNUSED_PARAM(size);
     UNUSED_PARAM(blendToPassthrough);
 
     ASSERT_NOT_REACHED();
diff --git a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
index ce414e1..60b1801 100644
--- a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
+++ b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
@@ -30,7 +30,6 @@
 #ifndef ValidatedCustomFilterOperation_h
 #define ValidatedCustomFilterOperation_h
 
-#include "core/platform/graphics/LayoutSize.h"
 #include "core/platform/graphics/filters/FilterOperation.h"
 #include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
 #include "core/platform/graphics/filters/custom/CustomFilterParameterList.h"
@@ -51,9 +50,8 @@
 
     virtual bool affectsOpacity() const { return true; }
     virtual bool movesPixels() const { return true; }
-    virtual bool blendingNeedsRendererSize() const { return true; }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, const LayoutSize&, bool blendToPassthrough = false);
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
 
     CustomFilterValidatedProgram* validatedProgram() const { return m_validatedProgram.get(); }
     const CustomFilterParameterList& parameters() const { return m_parameters; }
diff --git a/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm b/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm
index e5c514b..c5be0bb 100644
--- a/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm
+++ b/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm
@@ -275,12 +275,12 @@
                         m_complexTextRuns.append(ComplexTextRun::create(m_font.primaryFont(), cp, stringLocation + runRange.location, runRange.length, m_run.ltr()));
                         continue;
                     }
-                    runFontData = fontCache()->getCachedFontData(m_font.fontDescription(), fontName.get(), false, FontCache::DoNotRetain).get();
+                    runFontData = fontCache()->getFontResourceData(m_font.fontDescription(), fontName.get(), false, FontCache::DoNotRetain).get();
                     // Core Text may have used a font that is not known to NSFontManager. In that case, fall back on
                     // using the font as returned, even though it may not have the best NSFontRenderingMode.
                     if (!runFontData) {
                         FontPlatformData runFontPlatformData((NSFont *)runFont, CTFontGetSize(runFont), m_font.fontDescription().usePrinterFont());
-                        runFontData = fontCache()->getCachedFontData(&runFontPlatformData, FontCache::DoNotRetain).get();
+                        runFontData = fontCache()->getFontResourceData(&runFontPlatformData, FontCache::DoNotRetain).get();
                     }
                 }
                 if (m_fallbackFonts && runFontData != m_font.primaryFont())
diff --git a/Source/core/platform/graphics/mac/FontCacheMac.mm b/Source/core/platform/graphics/mac/FontCacheMac.mm
index d87f759..78c410e 100644
--- a/Source/core/platform/graphics/mac/FontCacheMac.mm
+++ b/Source/core/platform/graphics/mac/FontCacheMac.mm
@@ -170,7 +170,7 @@
         !font.isPlatformFont() && (traits & NSFontItalicTrait) && !(substituteFontTraits & NSFontItalicTrait),
         platformData.m_orientation);
 
-    return getCachedFontData(&alternateFont, DoNotRetain);
+    return getFontResourceData(&alternateFont, DoNotRetain);
 }
 
 PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
@@ -186,7 +186,7 @@
             DEFINE_STATIC_LOCAL(AtomicString, geezaStr, ("Geeza Pro", AtomicString::ConstructFromLiteral));
             for (int j = 0; j < 3 && !simpleFontData; ++j)
                 if (currFamily->family().contains(*matchWords[j], false))
-                    simpleFontData = getCachedFontData(font.fontDescription(), geezaStr);
+                    simpleFontData = getFontResourceData(font.fontDescription(), geezaStr);
         }
         currFamily = currFamily->next();
     }
@@ -200,7 +200,7 @@
 
     // FIXME: Would be even better to somehow get the user's default font here.  For now we'll pick
     // the default that the user would get without changing any prefs.
-    RefPtr<SimpleFontData> simpleFontData = getCachedFontData(fontDescription, timesStr, false, shouldRetain);
+    RefPtr<SimpleFontData> simpleFontData = getFontResourceData(fontDescription, timesStr, false, shouldRetain);
     if (simpleFontData)
         return simpleFontData.release();
 
@@ -209,7 +209,7 @@
     // guaranteed to be there, according to Nathan Taylor. This is good enough
     // to avoid a crash at least.
     DEFINE_STATIC_LOCAL(AtomicString, lucidaGrandeStr, ("Lucida Grande", AtomicString::ConstructFromLiteral));
-    return getCachedFontData(fontDescription, lucidaGrandeStr, false, shouldRetain);
+    return getFontResourceData(fontDescription, lucidaGrandeStr, false, shouldRetain);
 }
 
 void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
diff --git a/Source/core/platform/graphics/mac/SimpleFontDataMac.mm b/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
index cf920c4..c6df4cc 100644
--- a/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
+++ b/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
@@ -330,7 +330,7 @@
         scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
 
         // SimpleFontData::platformDestroy() takes care of not deleting the cached font data twice.
-        return fontCache()->getCachedFontData(&scaledFontData);
+        return fontCache()->getFontResourceData(&scaledFontData);
     }
     END_BLOCK_OBJC_EXCEPTIONS;
 
diff --git a/Source/core/platform/graphics/skia/FontCacheSkia.cpp b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
index 2aff081..14fafc3 100644
--- a/Source/core/platform/graphics/skia/FontCacheSkia.cpp
+++ b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
@@ -74,13 +74,13 @@
         description.setItalic(FontItalicOff);
     }
 
-    FontPlatformData* substitutePlatformData = getCachedFontPlatformData(description, atomicFamily, DoNotRetain);
+    FontPlatformData* substitutePlatformData = getFontResourcePlatformData(description, atomicFamily, DoNotRetain);
     if (!substitutePlatformData)
         return 0;
     FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
     platformData.setFakeBold(shouldSetFakeBold);
     platformData.setFakeItalic(shouldSetFakeItalic);
-    return getCachedFontData(&platformData, DoNotRetain);
+    return getFontResourceData(&platformData, DoNotRetain);
 }
 
 PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
@@ -94,11 +94,11 @@
     if (!fontPlatformData) {
         // we should at least have Arial; this is the SkFontHost_fontconfig last resort fallback
         DEFINE_STATIC_LOCAL(const AtomicString, arialStr, ("Arial", AtomicString::ConstructFromLiteral));
-        fontPlatformData = getCachedFontPlatformData(description, arialStr);
+        fontPlatformData = getFontResourcePlatformData(description, arialStr);
     }
 
     ASSERT(fontPlatformData);
-    return getCachedFontData(fontPlatformData, shouldRetain);
+    return getFontResourceData(fontPlatformData, shouldRetain);
 }
 
 void FontCache::getTraitsInFamily(const AtomicString& familyName,
diff --git a/Source/core/platform/graphics/skia/NativeImageSkia.cpp b/Source/core/platform/graphics/skia/NativeImageSkia.cpp
index 8e67530..dc81cd5 100644
--- a/Source/core/platform/graphics/skia/NativeImageSkia.cpp
+++ b/Source/core/platform/graphics/skia/NativeImageSkia.cpp
@@ -265,7 +265,7 @@
 {
 }
 
-NativeImageSkia::NativeImageSkia(const SkBitmap& image, float resolutionScale, const SkBitmap& resizedImage, const CachedImageInfo& cachedImageInfo, int resizeRequests)
+NativeImageSkia::NativeImageSkia(const SkBitmap& image, float resolutionScale, const SkBitmap& resizedImage, const ImageResourceInfo& cachedImageInfo, int resizeRequests)
     : m_image(image)
     , m_resolutionScale(resolutionScale)
     , m_resizedImage(resizedImage)
@@ -516,24 +516,24 @@
     return fragmentSize > fullSize / 4;
 }
 
-NativeImageSkia::CachedImageInfo::CachedImageInfo()
+NativeImageSkia::ImageResourceInfo::ImageResourceInfo()
 {
     scaledImageSize.setEmpty();
     scaledImageSubset.setEmpty();
 }
 
-bool NativeImageSkia::CachedImageInfo::isEqual(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset) const
+bool NativeImageSkia::ImageResourceInfo::isEqual(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset) const
 {
     return scaledImageSize == otherScaledImageSize && scaledImageSubset == otherScaledImageSubset;
 }
 
-void NativeImageSkia::CachedImageInfo::set(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset)
+void NativeImageSkia::ImageResourceInfo::set(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset)
 {
     scaledImageSize = otherScaledImageSize;
     scaledImageSubset = otherScaledImageSubset;
 }
 
-SkIRect NativeImageSkia::CachedImageInfo::rectInSubset(const SkIRect& otherScaledImageSubset)
+SkIRect NativeImageSkia::ImageResourceInfo::rectInSubset(const SkIRect& otherScaledImageSubset)
 {
     if (!scaledImageSubset.contains(otherScaledImageSubset))
         return SkIRect::MakeEmpty();
diff --git a/Source/core/platform/graphics/skia/NativeImageSkia.h b/Source/core/platform/graphics/skia/NativeImageSkia.h
index 6ca9e55..c26cf10 100644
--- a/Source/core/platform/graphics/skia/NativeImageSkia.h
+++ b/Source/core/platform/graphics/skia/NativeImageSkia.h
@@ -141,21 +141,21 @@
 
     NativeImageSkia(const SkBitmap&, float resolutionScale);
 
-    // CachedImageInfo is used to uniquely identify cached or requested image
+    // ImageResourceInfo is used to uniquely identify cached or requested image
     // resizes.
     // Image resize is identified by the scaled image size and scaled image subset.
-    struct CachedImageInfo {
+    struct ImageResourceInfo {
         SkISize scaledImageSize;
         SkIRect scaledImageSubset;
 
-        CachedImageInfo();
+        ImageResourceInfo();
 
         bool isEqual(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset) const;
         void set(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset);
         SkIRect rectInSubset(const SkIRect& otherScaledImageRect);
     };
 
-    NativeImageSkia(const SkBitmap& image, float resolutionScale, const SkBitmap& resizedImage, const CachedImageInfo&, int resizeRequests);
+    NativeImageSkia(const SkBitmap& image, float resolutionScale, const SkBitmap& resizedImage, const ImageResourceInfo&, int resizeRequests);
 
     // Returns true if the given resize operation should either resize the whole
     // image and cache it, or resize just the part it needs and throw the result
@@ -196,8 +196,8 @@
     // those requests individually are small and would not otherwise be cached.
     //
     // We also track scaling information and destination subset for the scaled
-    // image. See comments for CachedImageInfo.
-    mutable CachedImageInfo m_cachedImageInfo;
+    // image. See comments for ImageResourceInfo.
+    mutable ImageResourceInfo m_cachedImageInfo;
     mutable int m_resizeRequests;
 };
 
diff --git a/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp b/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp
new file mode 100644
index 0000000..8f0e2b0
--- /dev/null
+++ b/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/platform/graphics/transforms/InterpolatedTransformOperation.h"
+
+#include "core/platform/graphics/transforms/IdentityTransformOperation.h"
+
+namespace WebCore {
+
+bool InterpolatedTransformOperation::operator==(const TransformOperation& o) const
+{
+    if (!isSameType(o))
+        return false;
+    const InterpolatedTransformOperation* t = static_cast<const InterpolatedTransformOperation*>(&o);
+    return progress == t->progress && from == t->from && to == t->to;
+}
+
+bool InterpolatedTransformOperation::apply(TransformationMatrix& transform, const FloatSize& borderBoxSize) const
+{
+    TransformationMatrix fromTransform;
+    TransformationMatrix toTransform;
+    from.apply(borderBoxSize, fromTransform);
+    to.apply(borderBoxSize, toTransform);
+
+    toTransform.blend(fromTransform, progress);
+    transform.multiply(toTransform);
+    return true;
+}
+
+PassRefPtr<TransformOperation> InterpolatedTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
+{
+    if (from && !from->isSameType(*this))
+        return this;
+
+    TransformOperations thisOperations;
+    thisOperations.operations().append(this);
+    TransformOperations fromOperations;
+    if (blendToIdentity)
+        fromOperations.operations().append(IdentityTransformOperation::create());
+    else
+        fromOperations.operations().append(const_cast<TransformOperation*>(from));
+    return InterpolatedTransformOperation::create(thisOperations, fromOperations, progress);
+}
+
+} // namespace WebCore
+
diff --git a/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h b/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h
new file mode 100644
index 0000000..97ef8d5
--- /dev/null
+++ b/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef InterpolatedTransformOperation_h
+#define InterpolatedTransformOperation_h
+
+#include "core/platform/graphics/transforms/TransformOperation.h"
+#include "core/platform/graphics/transforms/TransformOperations.h"
+
+namespace WebCore {
+
+// This class is an implementation detail for deferred interpolations.
+class InterpolatedTransformOperation : public TransformOperation {
+public:
+    static PassRefPtr<InterpolatedTransformOperation> create(const TransformOperations& from, const TransformOperations& to, double progress)
+    {
+        return adoptRef(new InterpolatedTransformOperation(from, to, progress));
+    }
+
+private:
+    virtual bool isIdentity() const { return false; }
+
+    virtual OperationType getOperationType() const { return Interpolated; }
+    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Interpolated; }
+
+    virtual bool operator==(const TransformOperation&) const;
+    virtual bool apply(TransformationMatrix&, const FloatSize& borderBoxSize) const;
+
+    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
+
+    InterpolatedTransformOperation(const TransformOperations& from, const TransformOperations& to, double progress)
+        : from(from)
+        , to(to)
+        , progress(progress)
+    { }
+
+    const TransformOperations from;
+    const TransformOperations to;
+    double progress;
+};
+
+} // namespace WebCore
+
+#endif // InterpolatedTransformOperation_h
+
diff --git a/Source/core/platform/graphics/transforms/TransformOperation.h b/Source/core/platform/graphics/transforms/TransformOperation.h
index 2fb71ac..5223964 100644
--- a/Source/core/platform/graphics/transforms/TransformOperation.h
+++ b/Source/core/platform/graphics/transforms/TransformOperation.h
@@ -48,6 +48,7 @@
         RotateX, RotateY, Rotate3D,
         Matrix3D,
         Perspective,
+        Interpolated,
         Identity, None
     };
 
@@ -77,7 +78,8 @@
             || opType == RotateY
             || opType == Rotate3D
             || opType == Matrix3D
-            || opType == Perspective;
+            || opType == Perspective
+            || opType == Interpolated;
     }
 };
 
diff --git a/Source/core/platform/graphics/transforms/TransformOperations.cpp b/Source/core/platform/graphics/transforms/TransformOperations.cpp
index e4eabf1..bcca502 100644
--- a/Source/core/platform/graphics/transforms/TransformOperations.cpp
+++ b/Source/core/platform/graphics/transforms/TransformOperations.cpp
@@ -24,7 +24,7 @@
 
 #include <algorithm>
 #include "core/platform/graphics/transforms/IdentityTransformOperation.h"
-#include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
+#include "core/platform/graphics/transforms/InterpolatedTransformOperation.h"
 
 using namespace std;
 
@@ -90,25 +90,14 @@
     return result;
 }
 
-TransformOperations TransformOperations::blendByUsingMatrixInterpolation(const TransformOperations& from, double progress, const LayoutSize& size) const
+TransformOperations TransformOperations::blendByUsingMatrixInterpolation(const TransformOperations& from, double progress) const
 {
     TransformOperations result;
-
-    // Convert the TransformOperations into matrices
-    TransformationMatrix fromTransform;
-    TransformationMatrix toTransform;
-    from.apply(size, fromTransform);
-    apply(size, toTransform);
-
-    toTransform.blend(fromTransform, progress);
-
-    // Append the result
-    result.operations().append(Matrix3DTransformOperation::create(toTransform));
-
+    result.operations().append(InterpolatedTransformOperation::create(from, *this, progress));
     return result;
 }
 
-TransformOperations TransformOperations::blend(const TransformOperations& from, double progress, const LayoutSize& size) const
+TransformOperations TransformOperations::blend(const TransformOperations& from, double progress) const
 {
     if (from == *this)
         return *this;
@@ -116,7 +105,7 @@
     if (from.size() && from.operationsMatch(*this))
         return blendByMatchingOperations(from, progress);
 
-    return blendByUsingMatrixInterpolation(from, progress, size);
+    return blendByUsingMatrixInterpolation(from, progress);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/TransformOperations.h b/Source/core/platform/graphics/transforms/TransformOperations.h
index 7c43a95..f40f77f 100644
--- a/Source/core/platform/graphics/transforms/TransformOperations.h
+++ b/Source/core/platform/graphics/transforms/TransformOperations.h
@@ -35,7 +35,7 @@
 class TransformOperations {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    TransformOperations(bool makeIdentity = false);
+    explicit TransformOperations(bool makeIdentity = false);
 
     bool operator==(const TransformOperations& o) const;
     bool operator!=(const TransformOperations& o) const
@@ -73,8 +73,8 @@
     const TransformOperation* at(size_t index) const { return index < m_operations.size() ? m_operations.at(index).get() : 0; }
 
     TransformOperations blendByMatchingOperations(const TransformOperations& from, const double& progress) const;
-    TransformOperations blendByUsingMatrixInterpolation(const TransformOperations& from, double progress, const LayoutSize&) const;
-    TransformOperations blend(const TransformOperations& from, double progress, const LayoutSize&) const;
+    TransformOperations blendByUsingMatrixInterpolation(const TransformOperations& from, double progress) const;
+    TransformOperations blend(const TransformOperations& from, double progress) const;
 
 private:
     Vector<RefPtr<TransformOperation> > m_operations;
diff --git a/Source/core/platform/mac/ScrollbarThemeMac.h b/Source/core/platform/mac/ScrollbarThemeMac.h
index 5849d37..fac25ec 100644
--- a/Source/core/platform/mac/ScrollbarThemeMac.h
+++ b/Source/core/platform/mac/ScrollbarThemeMac.h
@@ -26,32 +26,32 @@
 #ifndef ScrollbarThemeMac_h
 #define ScrollbarThemeMac_h
 
-#include "core/platform/ScrollbarThemeComposite.h"
+#include "core/platform/ScrollbarTheme.h"
 
 namespace WebCore {
 
-class ScrollbarThemeMacCommon : public ScrollbarThemeComposite {
+class ScrollbarThemeMacCommon : public ScrollbarTheme {
 public:
     ScrollbarThemeMacCommon();
     virtual ~ScrollbarThemeMacCommon();
 
-    virtual void registerScrollbar(ScrollbarThemeClient*);
-    virtual void unregisterScrollbar(ScrollbarThemeClient*);
+    virtual void registerScrollbar(ScrollbarThemeClient*) OVERRIDE;
+    virtual void unregisterScrollbar(ScrollbarThemeClient*) OVERRIDE;
     void preferencesChanged();
 
-    virtual bool supportsControlTints() const { return true; }
+    virtual bool supportsControlTints() const OVERRIDE { return true; }
 
-    virtual double initialAutoscrollTimerDelay();
-    virtual double autoscrollTimerDelay();
+    virtual double initialAutoscrollTimerDelay() OVERRIDE;
+    virtual double autoscrollTimerDelay() OVERRIDE;
 
-    virtual void paintOverhangAreas(ScrollView*, GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect);
+    virtual void paintOverhangAreas(ScrollView*, GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect) OVERRIDE;
     virtual void paintTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
 
 protected:
-    virtual int maxOverlapBetweenPages() { return 40; }
+    virtual int maxOverlapBetweenPages() OVERRIDE { return 40; }
 
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
-    virtual bool shouldDragDocumentInsteadOfThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
+    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) OVERRIDE;
+    virtual bool shouldDragDocumentInsteadOfThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) OVERRIDE;
     int scrollbarPartToHIPressedState(ScrollbarPart);
 
     virtual void updateButtonPlacement() { }
diff --git a/Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.h b/Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.h
index a2345c7..2806605 100644
--- a/Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.h
+++ b/Source/core/platform/mac/ScrollbarThemeMacNonOverlayAPI.h
@@ -37,23 +37,23 @@
 
 class ScrollbarThemeMacNonOverlayAPI : public ScrollbarThemeMacCommon {
 public:
-    virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar);
-    virtual bool usesOverlayScrollbars() const { return false; }
-    virtual ScrollbarButtonsPlacement buttonsPlacement() const;
+    virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) OVERRIDE;
+    virtual bool usesOverlayScrollbars() const OVERRIDE { return false; }
+    virtual ScrollbarButtonsPlacement buttonsPlacement() const OVERRIDE;
 
-    virtual bool paint(ScrollbarThemeClient*, GraphicsContext*, const IntRect& damageRect);
+    virtual bool paint(ScrollbarThemeClient*, GraphicsContext*, const IntRect& damageRect) OVERRIDE;
 
 protected:
-    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false);
-    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
-    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
+    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
+    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
+    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
 
-    virtual void updateButtonPlacement();
+    virtual void updateButtonPlacement() OVERRIDE;
 
-    virtual bool hasButtons(ScrollbarThemeClient*);
-    virtual bool hasThumb(ScrollbarThemeClient*);
+    virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE;
+    virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
 
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+    virtual int minimumThumbLength(ScrollbarThemeClient*) OVERRIDE;
 };
 
 }
diff --git a/Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.h b/Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.h
index 890c3ce..f1712a0 100644
--- a/Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.h
+++ b/Source/core/platform/mac/ScrollbarThemeMacOverlayAPI.h
@@ -39,30 +39,30 @@
 
 class ScrollbarThemeMacOverlayAPI : public ScrollbarThemeMacCommon {
 public:
-    virtual void updateEnabledState(ScrollbarThemeClient*);
-    virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar);
-    virtual bool usesOverlayScrollbars() const;
-    virtual void updateScrollbarOverlayStyle(ScrollbarThemeClient*);
-    virtual ScrollbarButtonsPlacement buttonsPlacement() const;
+    virtual void updateEnabledState(ScrollbarThemeClient*) OVERRIDE;
+    virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) OVERRIDE;
+    virtual bool usesOverlayScrollbars() const OVERRIDE;
+    virtual void updateScrollbarOverlayStyle(ScrollbarThemeClient*) OVERRIDE;
+    virtual ScrollbarButtonsPlacement buttonsPlacement() const OVERRIDE;
 
-    virtual void registerScrollbar(ScrollbarThemeClient*);
-    virtual void unregisterScrollbar(ScrollbarThemeClient*);
+    virtual void registerScrollbar(ScrollbarThemeClient*) OVERRIDE;
+    virtual void unregisterScrollbar(ScrollbarThemeClient*) OVERRIDE;
 
     void setNewPainterForScrollbar(ScrollbarThemeClient*, ScrollbarPainter);
     ScrollbarPainter painterForScrollbar(ScrollbarThemeClient*);
 
-    virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
+    virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
+    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
 
 protected:
-    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false);
-    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
-    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
+    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
+    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
+    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
 
-    virtual bool hasButtons(ScrollbarThemeClient*) { return false; }
-    virtual bool hasThumb(ScrollbarThemeClient*);
+    virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE { return false; }
+    virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
 
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+    virtual int minimumThumbLength(ScrollbarThemeClient*) OVERRIDE;
 };
 
 }
diff --git a/Source/core/platform/mock/ScrollbarThemeMock.h b/Source/core/platform/mock/ScrollbarThemeMock.h
index 02284ee..3ddf026 100644
--- a/Source/core/platform/mock/ScrollbarThemeMock.h
+++ b/Source/core/platform/mock/ScrollbarThemeMock.h
@@ -26,29 +26,29 @@
 #ifndef ScrollbarThemeMock_h
 #define ScrollbarThemeMock_h
 
-#include "core/platform/ScrollbarThemeComposite.h"
+#include "core/platform/ScrollbarTheme.h"
 
 namespace WebCore {
 
 // Scrollbar theme used in image snapshots, to eliminate appearance differences between platforms.
-class ScrollbarThemeMock : public ScrollbarThemeComposite {
+class ScrollbarThemeMock : public ScrollbarTheme {
 public:
-    virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar);
+    virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) OVERRIDE;
     virtual bool usesOverlayScrollbars() const OVERRIDE;
 
 protected:
-    virtual bool hasButtons(ScrollbarThemeClient*) { return false; }
-    virtual bool hasThumb(ScrollbarThemeClient*) { return true; }
+    virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE { return false; }
+    virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE { return true; }
 
-    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool /*painting*/ = false) { return IntRect(); }
-    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool /*painting*/ = false) { return IntRect(); }
-    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false);
+    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool /*painting*/ = false) OVERRIDE { return IntRect(); }
+    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool /*painting*/ = false) OVERRIDE { return IntRect(); }
+    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
 
-    virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
+    virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
+    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
 
 private:
-    virtual bool isMockTheme() const { return true; }
+    virtual bool isMockTheme() const OVERRIDE FINAL { return true; }
 };
 
 }
diff --git a/Source/core/platform/network/HTTPParsers.cpp b/Source/core/platform/network/HTTPParsers.cpp
index 79e8e26..450c422 100644
--- a/Source/core/platform/network/HTTPParsers.cpp
+++ b/Source/core/platform/network/HTTPParsers.cpp
@@ -354,14 +354,14 @@
 
 ContentSecurityPolicy::ReflectedXSSDisposition parseXSSProtectionHeader(const String& header, String& failureReason, unsigned& failurePosition, String& reportURL)
 {
-    DEFINE_STATIC_LOCAL(String, failureReasonInvalidToggle, (ASCIILiteral("expected 0 or 1")));
-    DEFINE_STATIC_LOCAL(String, failureReasonInvalidSeparator, (ASCIILiteral("expected semicolon")));
-    DEFINE_STATIC_LOCAL(String, failureReasonInvalidEquals, (ASCIILiteral("expected equals sign")));
-    DEFINE_STATIC_LOCAL(String, failureReasonInvalidMode, (ASCIILiteral("invalid mode directive")));
-    DEFINE_STATIC_LOCAL(String, failureReasonInvalidReport, (ASCIILiteral("invalid report directive")));
-    DEFINE_STATIC_LOCAL(String, failureReasonDuplicateMode, (ASCIILiteral("duplicate mode directive")));
-    DEFINE_STATIC_LOCAL(String, failureReasonDuplicateReport, (ASCIILiteral("duplicate report directive")));
-    DEFINE_STATIC_LOCAL(String, failureReasonInvalidDirective, (ASCIILiteral("unrecognized directive")));
+    DEFINE_STATIC_LOCAL(String, failureReasonInvalidToggle, ("expected 0 or 1"));
+    DEFINE_STATIC_LOCAL(String, failureReasonInvalidSeparator, ("expected semicolon"));
+    DEFINE_STATIC_LOCAL(String, failureReasonInvalidEquals, ("expected equals sign"));
+    DEFINE_STATIC_LOCAL(String, failureReasonInvalidMode, ("invalid mode directive"));
+    DEFINE_STATIC_LOCAL(String, failureReasonInvalidReport, ("invalid report directive"));
+    DEFINE_STATIC_LOCAL(String, failureReasonDuplicateMode, ("duplicate mode directive"));
+    DEFINE_STATIC_LOCAL(String, failureReasonDuplicateReport, ("duplicate report directive"));
+    DEFINE_STATIC_LOCAL(String, failureReasonInvalidDirective, ("unrecognized directive"));
 
     unsigned pos = 0;
 
diff --git a/Source/core/platform/network/ResourceLoadTiming.h b/Source/core/platform/network/ResourceLoadTiming.h
index c6debdd..56025d1 100644
--- a/Source/core/platform/network/ResourceLoadTiming.h
+++ b/Source/core/platform/network/ResourceLoadTiming.h
@@ -98,7 +98,7 @@
     double sslStart;
     double sslEnd;
 
-    double calculateMillisecondDelta(double time) const { return (time - requestTime) * 1000; }
+    double calculateMillisecondDelta(double time) const { return time ? (time - requestTime) * 1000 : -1; }
 
 private:
     ResourceLoadTiming()
diff --git a/Source/core/platform/network/ResourceRequest.h b/Source/core/platform/network/ResourceRequest.h
index 456d7c0..d54305a 100644
--- a/Source/core/platform/network/ResourceRequest.h
+++ b/Source/core/platform/network/ResourceRequest.h
@@ -56,7 +56,7 @@
             TargetIsSubresource, // Resource is a generic subresource. (Generally a specific type should be specified)
             TargetIsStyleSheet,
             TargetIsScript,
-            TargetIsFontResource,
+            TargetIsFont,
             TargetIsImage,
             TargetIsObject,
             TargetIsMedia,
diff --git a/Source/core/platform/sql/SQLiteDatabase.cpp b/Source/core/platform/sql/SQLiteDatabase.cpp
index aa41021..5035f1e 100644
--- a/Source/core/platform/sql/SQLiteDatabase.cpp
+++ b/Source/core/platform/sql/SQLiteDatabase.cpp
@@ -95,7 +95,7 @@
     else
         m_openErrorMessage = "sqlite_open returned null";
 
-    if (!SQLiteStatement(*this, ASCIILiteral("PRAGMA temp_store = MEMORY;")).executeCommand())
+    if (!SQLiteStatement(*this, "PRAGMA temp_store = MEMORY;").executeCommand())
         LOG_ERROR("SQLite database could not set temp_store to memory");
 
     return isOpen();
@@ -142,9 +142,9 @@
 void SQLiteDatabase::setFullsync(bool fsync)
 {
     if (fsync)
-        executeCommand(ASCIILiteral("PRAGMA fullfsync = 1;"));
+        executeCommand("PRAGMA fullfsync = 1;");
     else
-        executeCommand(ASCIILiteral("PRAGMA fullfsync = 0;"));
+        executeCommand("PRAGMA fullfsync = 0;");
 }
 
 int64_t SQLiteDatabase::maximumSize()
@@ -154,7 +154,7 @@
     {
         MutexLocker locker(m_authorizerLock);
         enableAuthorizer(false);
-        SQLiteStatement statement(*this, ASCIILiteral("PRAGMA max_page_count"));
+        SQLiteStatement statement(*this, "PRAGMA max_page_count");
         maxPageCount = statement.getColumnInt64(0);
         enableAuthorizer(true);
     }
@@ -196,7 +196,7 @@
         MutexLocker locker(m_authorizerLock);
         enableAuthorizer(false);
 
-        SQLiteStatement statement(*this, ASCIILiteral("PRAGMA page_size"));
+        SQLiteStatement statement(*this, "PRAGMA page_size");
         m_pageSize = statement.getColumnInt(0);
 
         enableAuthorizer(true);
@@ -213,7 +213,7 @@
         MutexLocker locker(m_authorizerLock);
         enableAuthorizer(false);
         // Note: freelist_count was added in SQLite 3.4.1.
-        SQLiteStatement statement(*this, ASCIILiteral("PRAGMA freelist_count"));
+        SQLiteStatement statement(*this, "PRAGMA freelist_count");
         freelistCount = statement.getColumnInt64(0);
         enableAuthorizer(true);
     }
@@ -228,7 +228,7 @@
     {
         MutexLocker locker(m_authorizerLock);
         enableAuthorizer(false);
-        SQLiteStatement statement(*this, ASCIILiteral("PRAGMA page_count"));
+        SQLiteStatement statement(*this, "PRAGMA page_count");
         pageCount = statement.getColumnInt64(0);
         enableAuthorizer(true);
     }
@@ -281,7 +281,7 @@
 
 void SQLiteDatabase::clearAllTables()
 {
-    String query = ASCIILiteral("SELECT name FROM sqlite_master WHERE type='table';");
+    String query = "SELECT name FROM sqlite_master WHERE type='table';";
     Vector<String> tables;
     if (!SQLiteStatement(*this, query).returnTextResults(0, tables)) {
         LOG(SQLDatabase, "Unable to retrieve list of tables from database");
@@ -298,7 +298,7 @@
 
 int SQLiteDatabase::runVacuumCommand()
 {
-    if (!executeCommand(ASCIILiteral("VACUUM;")))
+    if (!executeCommand("VACUUM;"))
         LOG(SQLDatabase, "Unable to vacuum database - %s", lastErrorMsg());
     return lastError();
 }
@@ -308,7 +308,7 @@
     MutexLocker locker(m_authorizerLock);
     enableAuthorizer(false);
 
-    if (!executeCommand(ASCIILiteral("PRAGMA incremental_vacuum")))
+    if (!executeCommand("PRAGMA incremental_vacuum"))
         LOG(SQLDatabase, "Unable to run incremental vacuum - %s", lastErrorMsg());
 
     enableAuthorizer(true);
@@ -468,7 +468,7 @@
 
 bool SQLiteDatabase::turnOnIncrementalAutoVacuum()
 {
-    SQLiteStatement statement(*this, ASCIILiteral("PRAGMA auto_vacuum"));
+    SQLiteStatement statement(*this, "PRAGMA auto_vacuum");
     int autoVacuumMode = statement.getColumnInt(0);
     int error = lastError();
 
@@ -485,10 +485,10 @@
     case AutoVacuumIncremental:
         return true;
     case AutoVacuumFull:
-        return executeCommand(ASCIILiteral("PRAGMA auto_vacuum = 2"));
+        return executeCommand("PRAGMA auto_vacuum = 2");
     case AutoVacuumNone:
     default:
-        if (!executeCommand(ASCIILiteral("PRAGMA auto_vacuum = 2")))
+        if (!executeCommand("PRAGMA auto_vacuum = 2"))
             return false;
         runVacuumCommand();
         error = lastError();
diff --git a/Source/core/platform/text/DateTimeFormat.cpp b/Source/core/platform/text/DateTimeFormat.cpp
index 5cbb644..6cf33d4 100644
--- a/Source/core/platform/text/DateTimeFormat.cpp
+++ b/Source/core/platform/text/DateTimeFormat.cpp
@@ -267,7 +267,7 @@
             buffer.append("''");
         else {
             String escaped = literal.substring(i);
-            escaped.replace(ASCIILiteral("'"), ASCIILiteral("''"));
+            escaped.replace("'", "''");
             buffer.append("'");
             buffer.append(escaped);
             buffer.append("'");
diff --git a/Source/core/platform/text/LocaleICU.cpp b/Source/core/platform/text/LocaleICU.cpp
index e94fed9..7b5efcd 100644
--- a/Source/core/platform/text/LocaleICU.cpp
+++ b/Source/core/platform/text/LocaleICU.cpp
@@ -311,14 +311,14 @@
     if (!m_dateFormat.isNull())
         return m_dateFormat;
     if (!initializeShortDateFormat())
-        return ASCIILiteral("yyyy-MM-dd");
+        return "yyyy-MM-dd";
     m_dateFormat = getDateFormatPattern(m_shortDateFormat);
     return m_dateFormat;
 }
 
 static String getFormatForSkeleton(const char* locale, const String& skeleton)
 {
-    String format = ASCIILiteral("yyyy-MM");
+    String format = "yyyy-MM";
     UErrorCode status = U_ZERO_ERROR;
     UDateTimePatternGenerator* patternGenerator = udatpg_open(locale, &status);
     if (!patternGenerator)
@@ -344,7 +344,7 @@
         return m_monthFormat;
     // Gets a format for "MMMM" because Windows API always provides formats for
     // "MMMM" in some locales.
-    m_monthFormat = getFormatForSkeleton(m_locale.data(), ASCIILiteral("yyyyMMMM"));
+    m_monthFormat = getFormatForSkeleton(m_locale.data(), "yyyyMMMM");
     return m_monthFormat;
 }
 
@@ -352,7 +352,7 @@
 {
     if (!m_shortMonthFormat.isNull())
         return m_shortMonthFormat;
-    m_shortMonthFormat = getFormatForSkeleton(m_locale.data(), ASCIILiteral("yyyyMMM"));
+    m_shortMonthFormat = getFormatForSkeleton(m_locale.data(), "yyyyMMM");
     return m_shortMonthFormat;
 }
 
diff --git a/Source/core/platform/text/TextBreakIteratorICU.cpp b/Source/core/platform/text/TextBreakIteratorICU.cpp
index 6407b72..a093a94 100644
--- a/Source/core/platform/text/TextBreakIteratorICU.cpp
+++ b/Source/core/platform/text/TextBreakIteratorICU.cpp
@@ -720,7 +720,7 @@
         UParseError parseStatus;
         UErrorCode openStatus = U_ZERO_ERROR;
         Vector<UChar> rules;
-        String(ASCIILiteral(breakRules)).appendTo(rules);
+        String(breakRules).appendTo(rules);
         iterator = reinterpret_cast<TextBreakIterator*>(ubrk_openRules(rules.data(), rules.size(), 0, 0, &parseStatus, &openStatus));
         createdIterator = true;
         ASSERT_WITH_MESSAGE(U_SUCCESS(openStatus), "ICU could not open a break iterator: %s (%d)", u_errorName(openStatus), openStatus);
diff --git a/Source/core/rendering/CompositingReasons.h b/Source/core/rendering/CompositingReasons.h
index 0e35e82..5940c09 100644
--- a/Source/core/rendering/CompositingReasons.h
+++ b/Source/core/rendering/CompositingReasons.h
@@ -54,6 +54,10 @@
 const uint64_t CompositingReasonLayerForBackground                     = UINT64_C(1) << 30;
 const uint64_t CompositingReasonLayerForMask                           = UINT64_C(1) << 31;
 
+// FIXME: the following compositing reasons need to be re-organized to fit with categories
+// used in all the other reasons above.
+const uint64_t CompositingReasonLayerForVideoOverlay                   = UINT64_C(1) << 32;
+
 // Note: if you add more reasons here, you will need to update WebCompositingReasons as well.
 typedef uint64_t CompositingReasons;
 
diff --git a/Source/core/rendering/FilterEffectRenderer.cpp b/Source/core/rendering/FilterEffectRenderer.cpp
index 85d6c07..ea8f36e 100644
--- a/Source/core/rendering/FilterEffectRenderer.cpp
+++ b/Source/core/rendering/FilterEffectRenderer.cpp
@@ -29,8 +29,8 @@
 #include "core/rendering/FilterEffectRenderer.h"
 
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedDocument.h"
-#include "core/loader/cache/CachedSVGDocumentReference.h"
+#include "core/loader/cache/DocumentResource.h"
+#include "core/loader/cache/DocumentResourceReference.h"
 #include "core/page/Page.h"
 #include "core/platform/FloatConversion.h"
 #include "core/platform/graphics/ColorSpace.h"
diff --git a/Source/core/rendering/FilterEffectRenderer.h b/Source/core/rendering/FilterEffectRenderer.h
index 5352713..2dfe268 100644
--- a/Source/core/rendering/FilterEffectRenderer.h
+++ b/Source/core/rendering/FilterEffectRenderer.h
@@ -42,7 +42,7 @@
 
 namespace WebCore {
 
-class CachedShader;
+class ShaderResource;
 class CustomFilterProgram;
 class Document;
 class GraphicsContext;
diff --git a/Source/core/rendering/FlowThreadController.h b/Source/core/rendering/FlowThreadController.h
index b7deda8..7f56615 100644
--- a/Source/core/rendering/FlowThreadController.h
+++ b/Source/core/rendering/FlowThreadController.h
@@ -55,7 +55,7 @@
     {
         m_isRenderNamedFlowThreadOrderDirty = dirty;
         if (dirty)
-            m_view->setNeedsLayout(true);
+            m_view->setNeedsLayout();
     }
 
     RenderNamedFlowThread* ensureRenderFlowThreadWithName(const AtomicString&);
diff --git a/Source/core/rendering/HitTestLocation.cpp b/Source/core/rendering/HitTestLocation.cpp
index 19642db..96c55ae 100644
--- a/Source/core/rendering/HitTestLocation.cpp
+++ b/Source/core/rendering/HitTestLocation.cpp
@@ -34,7 +34,7 @@
 #include "core/html/HTMLPlugInImageElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/platform/Scrollbar.h"
diff --git a/Source/core/rendering/HitTestResult.cpp b/Source/core/rendering/HitTestResult.cpp
index 5fd0969..393d2cb 100644
--- a/Source/core/rendering/HitTestResult.cpp
+++ b/Source/core/rendering/HitTestResult.cpp
@@ -37,7 +37,7 @@
 #include "core/html/HTMLTextAreaElement.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/platform/Scrollbar.h"
diff --git a/Source/core/rendering/InlineTextBox.cpp b/Source/core/rendering/InlineTextBox.cpp
index e2eeae0..2bfe7de 100644
--- a/Source/core/rendering/InlineTextBox.cpp
+++ b/Source/core/rendering/InlineTextBox.cpp
@@ -28,6 +28,7 @@
 #include "core/dom/RenderedDocumentMarker.h"
 #include "core/dom/Text.h"
 #include "core/editing/Editor.h"
+#include "core/editing/InputMethodController.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
@@ -47,6 +48,7 @@
 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
 #include "wtf/Vector.h"
 #include "wtf/text/CString.h"
+#include "wtf/text/StringBuilder.h"
 
 using namespace std;
 
@@ -186,16 +188,6 @@
     return state;
 }
 
-static void adjustCharactersAndLengthForHyphen(BufferForAppendingHyphen& charactersWithHyphen, RenderStyle* style, StringView& string, int& length)
-{
-    const AtomicString& hyphenString = style->hyphenString();
-    charactersWithHyphen.reserveCapacity(length + hyphenString.length());
-    charactersWithHyphen.append(string);
-    charactersWithHyphen.append(hyphenString);
-    string = charactersWithHyphen.toString().createView();
-    length += hyphenString.length();
-}
-
 LayoutRect InlineTextBox::localSelectionRect(int startPos, int endPos)
 {
     int sPos = max(startPos - m_start, 0);
@@ -212,7 +204,7 @@
     RenderStyle* styleToUse = textObj->style(isFirstLineStyle());
     const Font& font = styleToUse->font();
 
-    BufferForAppendingHyphen charactersWithHyphen;
+    StringBuilder charactersWithHyphen;
     bool respectHyphen = ePos == m_len && hasHyphen();
     TextRun textRun = constructTextRun(styleToUse, font, respectHyphen ? &charactersWithHyphen : 0);
     if (respectHyphen)
@@ -545,8 +537,8 @@
         context->concatCTM(rotation(boxRect, Clockwise));
 
     // Determine whether or not we have composition underlines to draw.
-    bool containsComposition = renderer()->node() && renderer()->frame()->editor()->compositionNode() == renderer()->node();
-    bool useCustomUnderlines = containsComposition && renderer()->frame()->editor()->compositionUsesCustomUnderlines();
+    bool containsComposition = renderer()->node() && renderer()->frame()->inputMethodController().compositionNode() == renderer()->node();
+    bool useCustomUnderlines = containsComposition && renderer()->frame()->inputMethodController().compositionUsesCustomUnderlines();
 
     // Determine the text colors and selection colors.
     Color textFillColor;
@@ -650,10 +642,11 @@
     // and composition underlines.
     if (paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseTextClip && !isPrinting) {
 
-        if (containsComposition && !useCustomUnderlines)
+        if (containsComposition && !useCustomUnderlines) {
             paintCompositionBackground(context, boxOrigin, styleToUse, font,
-                renderer()->frame()->editor()->compositionStart(),
-                renderer()->frame()->editor()->compositionEnd());
+                renderer()->frame()->inputMethodController().compositionStart(),
+                renderer()->frame()->inputMethodController().compositionEnd());
+        }
 
         paintDocumentMarkers(context, boxOrigin, styleToUse, font, true);
 
@@ -686,7 +679,7 @@
         maximumLength = length;
     }
 
-    BufferForAppendingHyphen charactersWithHyphen;
+    StringBuilder charactersWithHyphen;
     TextRun textRun = constructTextRun(styleToUse, font, string, maximumLength, hasHyphen() ? &charactersWithHyphen : 0);
     if (hasHyphen())
         length = textRun.length();
@@ -780,7 +773,7 @@
         paintDocumentMarkers(context, boxOrigin, styleToUse, font, false);
 
         if (useCustomUnderlines) {
-            const Vector<CompositionUnderline>& underlines = renderer()->frame()->editor()->customCompositionUnderlines();
+            const Vector<CompositionUnderline>& underlines = renderer()->frame()->inputMethodController().customCompositionUnderlines();
             size_t numUnderlines = underlines.size();
 
             for (size_t index = 0; index < numUnderlines; ++index) {
@@ -865,7 +858,7 @@
     if (string.length() != static_cast<unsigned>(length) || m_start)
         string.narrow(m_start, length);
 
-    BufferForAppendingHyphen charactersWithHyphen;
+    StringBuilder charactersWithHyphen;
     bool respectHyphen = ePos == length && hasHyphen();
     TextRun textRun = constructTextRun(style, font, string, textRenderer()->textLength() - m_start, respectHyphen ? &charactersWithHyphen : 0);
     if (respectHyphen)
@@ -1494,7 +1487,7 @@
     return true;
 }
 
-TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, BufferForAppendingHyphen* charactersWithHyphen) const
+TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, StringBuilder* charactersWithHyphen) const
 {
     ASSERT(style);
 
@@ -1512,21 +1505,23 @@
     return constructTextRun(style, font, string, textRenderer->textLength() - startPos, charactersWithHyphen);
 }
 
-TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, StringView string, int maximumLength, BufferForAppendingHyphen* charactersWithHyphen) const
+TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, StringView string, int maximumLength, StringBuilder* charactersWithHyphen) const
 {
     ASSERT(style);
 
     RenderText* textRenderer = this->textRenderer();
     ASSERT(textRenderer);
 
-    int length = string.length();
-
     if (charactersWithHyphen) {
-        adjustCharactersAndLengthForHyphen(*charactersWithHyphen, style, string, length);
-        maximumLength = length;
+        const AtomicString& hyphenString = style->hyphenString();
+        charactersWithHyphen->reserveCapacity(string.length() + hyphenString.length());
+        charactersWithHyphen->append(string);
+        charactersWithHyphen->append(hyphenString);
+        string = charactersWithHyphen->toString().createView();
+        maximumLength = string.length();
     }
 
-    ASSERT(maximumLength >= length);
+    ASSERT(maximumLength >= static_cast<int>(string.length()));
 
     TextRun run(string, textPos(), expansion(), expansionBehavior(), direction(), dirOverride() || style->rtlOrdering() == VisualOrder, !textRenderer->canUseSimpleFontCodePath());
     run.setTabSize(!style->collapseWhiteSpace(), style->tabSize());
diff --git a/Source/core/rendering/InlineTextBox.h b/Source/core/rendering/InlineTextBox.h
index 8778f97..ed4d663 100644
--- a/Source/core/rendering/InlineTextBox.h
+++ b/Source/core/rendering/InlineTextBox.h
@@ -26,7 +26,7 @@
 #include "core/platform/graphics/TextRun.h"
 #include "core/rendering/InlineBox.h"
 #include "core/rendering/RenderText.h" // so textRenderer() can be inline
-#include "wtf/text/StringBuilder.h"
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
@@ -36,11 +36,6 @@
 const unsigned short cNoTruncation = USHRT_MAX;
 const unsigned short cFullTruncation = USHRT_MAX - 1;
 
-class BufferForAppendingHyphen : public StringBuilder {
-public:
-    BufferForAppendingHyphen() { reserveCapacity(256); }
-};
-
 // Helper functions shared by InlineTextBox / SVGRootInlineBox
 void updateGraphicsContext(GraphicsContext*, const Color& fillColor, const Color& strokeColor, float strokeThickness, ColorSpace);
 Color correctedTextColor(Color textColor, Color backgroundColor);
@@ -107,8 +102,9 @@
     LayoutUnit selectionBottom();
     LayoutUnit selectionHeight();
 
-    TextRun constructTextRun(RenderStyle*, const Font&, BufferForAppendingHyphen* = 0) const;
-    TextRun constructTextRun(RenderStyle*, const Font&, StringView, int maximumLength, BufferForAppendingHyphen* = 0) const;
+    // charactersWithHyphen, if provided, must not be destroyed before the TextRun.
+    TextRun constructTextRun(RenderStyle*, const Font&, StringBuilder* charactersWithHyphen = 0) const;
+    TextRun constructTextRun(RenderStyle*, const Font&, StringView, int maximumLength, StringBuilder* charactersWithHyphen = 0) const;
 
 public:
     virtual FloatRect calculateBoundaries() const { return FloatRect(x(), y(), width(), height()); }
diff --git a/Source/core/rendering/RenderBR.cpp b/Source/core/rendering/RenderBR.cpp
index 27fa7c7..c463047 100644
--- a/Source/core/rendering/RenderBR.cpp
+++ b/Source/core/rendering/RenderBR.cpp
@@ -28,7 +28,7 @@
 
 static PassRefPtr<StringImpl> newlineString()
 {
-    DEFINE_STATIC_LOCAL(const String, string, (ASCIILiteral("\n")));
+    DEFINE_STATIC_LOCAL(const String, string, ("\n"));
     return string.impl();
 }
 
diff --git a/Source/core/rendering/RenderBlock.cpp b/Source/core/rendering/RenderBlock.cpp
index 7bcd381..5c7a9d9 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -1699,7 +1699,7 @@
         }
     }
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderBlock::addOverflowFromChildren()
@@ -1714,8 +1714,7 @@
         if (columnCount(colInfo)) {
             LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
             addLayoutOverflow(lastRect);
-            if (!hasOverflowClip())
-                addVisualOverflow(lastRect);
+            addContentsVisualOverflow(lastRect);
         }
     }
 }
@@ -1752,8 +1751,8 @@
     LayoutUnit textIndent = textIndentOffset();
     if (textIndent < 0) {
         LayoutRect clientRect(noOverflowRect());
-        LayoutRect rectToApply = LayoutRect(clientRect.x() + min<LayoutUnit>(0, textIndent), clientRect.y(), clientRect.width() - min<LayoutUnit>(0, textIndent), clientRect.height());
-        addVisualOverflow(rectToApply);
+        LayoutRect rectToApply = LayoutRect(clientRect.x() + textIndent, clientRect.y(), clientRect.width() - textIndent, clientRect.height());
+        addContentsVisualOverflow(rectToApply);
     }
 
     // Add visual overflow from box-shadow and border-image-outset.
@@ -1845,7 +1844,7 @@
     if (childLayer->staticBlockPosition() != logicalTop) {
         childLayer->setStaticBlockPosition(logicalTop);
         if (hasStaticBlockPosition)
-            child->setChildNeedsLayout(true, MarkOnlyThis);
+            child->setChildNeedsLayout(MarkOnlyThis);
     }
 }
 
@@ -2449,7 +2448,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->setChildNeedsLayout(true, MarkOnlyThis);
+        child->setChildNeedsLayout(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.
     if (relayoutChildren && child->needsPreferredWidthsRecalculation())
@@ -2466,7 +2465,7 @@
                 while (box != this) {
                     if (box->normalChildNeedsLayout())
                         break;
-                    box->setChildNeedsLayout(true, MarkOnlyThis);
+                    box->setChildNeedsLayout(MarkOnlyThis);
                     box = box->containingBlock();
                     ASSERT(box);
                     if (!box)
@@ -2610,7 +2609,7 @@
             // When the child shifts to clear an item, its width can
             // change (because it has more available line width).
             // So go ahead and mark the item as dirty.
-            child->setChildNeedsLayout(true, MarkOnlyThis);
+            child->setChildNeedsLayout(MarkOnlyThis);
         }
 
         if (childRenderBlock) {
@@ -2681,8 +2680,9 @@
                     RootInlineBox* box = toRenderBox(o)->inlineBoxWrapper()->root();
                     lineBoxes.add(box);
                 }
-            } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
-                o->setNeedsLayout(false);
+            } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline())) {
+                o->clearNeedsLayout();
+            }
         }
 
         // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
@@ -2738,7 +2738,7 @@
 
     updateScrollInfoAfterLayout();
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
     return true;
 }
 
@@ -2763,12 +2763,12 @@
         LayoutUnit oldLeft = box->logicalLeft();
         box->updateLogicalWidth();
         if (box->logicalLeft() != oldLeft)
-            child->setChildNeedsLayout(true, MarkOnlyThis);
+            child->setChildNeedsLayout(MarkOnlyThis);
     } else if (hasStaticBlockPosition) {
         LayoutUnit oldTop = box->logicalTop();
         box->updateLogicalHeight();
         if (box->logicalTop() != oldTop)
-            child->setChildNeedsLayout(true, MarkOnlyThis);
+            child->setChildNeedsLayout(MarkOnlyThis);
     }
 }
 
@@ -2800,7 +2800,7 @@
         // objects that are positioned implicitly like this.  Such objects are rare, and so in typical DHTML menu usage (where everything is
         // positioned explicitly) this should not incur a performance penalty.
         if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
-            r->setChildNeedsLayout(true, MarkOnlyThis);
+            r->setChildNeedsLayout(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.
         if (relayoutChildren && r->needsPreferredWidthsRecalculation())
@@ -2812,7 +2812,7 @@
         // We don't have to do a full layout.  We just have to update our position. Try that first. If we have shrink-to-fit width
         // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
         if (r->needsPositionedMovementLayoutOnly() && r->tryLayoutDoingPositionedMovementOnly())
-            r->setNeedsLayout(false);
+            r->clearNeedsLayout();
 
         // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
         // If it's wrong we'll lay out again.
@@ -2845,7 +2845,7 @@
         TrackedRendererListHashSet::iterator end = positionedDescendants->end();
         for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
             r = *it;
-            r->setChildNeedsLayout(true);
+            r->setChildNeedsLayout();
         }
     }
 }
@@ -2857,7 +2857,7 @@
         return;
 
     if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()) || shouldBreakAtLineToAvoidWidow())
-        setChildNeedsLayout(true, MarkOnlyThis);
+        setChildNeedsLayout(MarkOnlyThis);
 }
 
 void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
@@ -2904,7 +2904,13 @@
             return;
     }
 
-    bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
+    // There are some cases where not all clipped visual overflow is accounted for.
+    // FIXME: reduce the number of such cases.
+    ContentsClipBehavior contentsClipBehavior = ForceContentsClip;
+    if (hasOverflowClip() && !hasControlClip() && !(shouldPaintSelectionGaps() && phase == PaintPhaseForeground) && !hasCaret())
+        contentsClipBehavior = SkipContentsClipIfPossible;
+
+    bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset, contentsClipBehavior);
     paintObject(paintInfo, adjustedPaintOffset);
     if (pushedClip)
         popContentsClip(paintInfo, phase, adjustedPaintOffset);
@@ -3097,8 +3103,7 @@
         child->paint(paintInfo, childPoint);
 }
 
-
-void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
+bool RenderBlock::hasCaret(CaretType type) const
 {
     // Paint the caret if the FrameSelection says so or if caret browsing is enabled
     bool caretBrowsing = frame()->settings() && frame()->settings()->caretBrowsingEnabled();
@@ -3111,13 +3116,18 @@
         caretPainter = frame()->page()->dragCaretController()->caretRenderer();
         isContentEditable = frame()->page()->dragCaretController()->isContentEditable();
     }
+    return caretPainter == this && (isContentEditable || caretBrowsing);
+}
 
-    if (caretPainter == this && (isContentEditable || caretBrowsing)) {
-        if (type == CursorCaret)
-            frame()->selection()->paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
-        else
-            frame()->page()->dragCaretController()->paintDragCaret(frame(), paintInfo.context, paintOffset, paintInfo.rect);
-    }
+void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
+{
+    if (!hasCaret(type))
+        return;
+
+    if (type == CursorCaret)
+        frame()->selection()->paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
+    else
+        frame()->page()->dragCaretController()->paintDragCaret(frame(), paintInfo.context, paintOffset, paintInfo.rect);
 }
 
 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
@@ -3836,7 +3846,7 @@
         r = *it;
         if (!o || r->isDescendantOf(o)) {
             if (containingBlockState == NewContainingBlock)
-                r->setChildNeedsLayout(true, MarkOnlyThis);
+                r->setChildNeedsLayout(MarkOnlyThis);
 
             // It is parent blocks job to add positioned child to positioned objects list of its containing block
             // Parent layout needs to be invalidated to ensure this happens.
@@ -3844,7 +3854,7 @@
             while (p && !p->isRenderBlock())
                 p = p->parent();
             if (p)
-                p->setChildNeedsLayout(true);
+                p->setChildNeedsLayout();
 
             deadObjects.append(r);
         }
@@ -3886,7 +3896,7 @@
     // Just go ahead and lay out the float.
     bool isChildRenderBlock = o->isRenderBlock();
     if (isChildRenderBlock && !o->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
-        o->setChildNeedsLayout(true, MarkOnlyThis);
+        o->setChildNeedsLayout(MarkOnlyThis);
 
     bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
     if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) // We are unsplittable if we're a block flow root.
@@ -4118,7 +4128,7 @@
                 setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
 
                 if (childBlock)
-                    childBlock->setChildNeedsLayout(true, MarkOnlyThis);
+                    childBlock->setChildNeedsLayout(MarkOnlyThis);
                 childBox->layoutIfNeeded();
             }
         }
@@ -4236,31 +4246,42 @@
     return false;
 }
 
+template<>
+bool RenderBlock::FloatIntervalSearchAdapter<RenderBlock::FloatingObject::FloatLeft>::updateOffsetIfNeeded(const FloatingObject* floatingObject) const
+{
+    if (m_renderer->logicalRightForFloat(floatingObject) > m_offset) {
+        m_offset = m_renderer->logicalRightForFloat(floatingObject);
+        return true;
+    }
+    return false;
+}
+
+template<>
+bool RenderBlock::FloatIntervalSearchAdapter<RenderBlock::FloatingObject::FloatRight>::updateOffsetIfNeeded(const FloatingObject* floatingObject) const
+{
+    if (m_renderer->logicalLeftForFloat(floatingObject) < m_offset) {
+        m_offset = m_renderer->logicalLeftForFloat(floatingObject);
+        return true;
+    }
+    return false;
+}
+
 template <RenderBlock::FloatingObject::Type FloatTypeValue>
 inline void RenderBlock::FloatIntervalSearchAdapter<FloatTypeValue>::collectIfNeeded(const IntervalType& interval) const
 {
-    const FloatingObject* r = interval.data();
-    if (r->type() != FloatTypeValue || !rangesIntersect(interval.low(), interval.high(), m_lowValue, m_highValue))
+    const FloatingObject* floatingObject = interval.data();
+    if (floatingObject->type() != FloatTypeValue || !rangesIntersect(interval.low(), interval.high(), m_lowValue, m_highValue))
         return;
 
     // All the objects returned from the tree should be already placed.
-    ASSERT(r->isPlaced() && rangesIntersect(m_renderer->pixelSnappedLogicalTopForFloat(r), m_renderer->pixelSnappedLogicalBottomForFloat(r), m_lowValue, m_highValue));
+    ASSERT(floatingObject->isPlaced());
+    ASSERT(rangesIntersect(m_renderer->pixelSnappedLogicalTopForFloat(floatingObject), m_renderer->pixelSnappedLogicalBottomForFloat(floatingObject), m_lowValue, m_highValue));
 
-    if (FloatTypeValue == FloatingObject::FloatLeft
-        && m_renderer->logicalRightForFloat(r) > m_offset) {
-        m_offset = m_renderer->logicalRightForFloat(r);
-        if (m_heightRemaining)
-            *m_heightRemaining = m_renderer->logicalBottomForFloat(r) - m_lowValue;
-    }
+    bool floatIsNewExtreme = updateOffsetIfNeeded(floatingObject);
+    if (floatIsNewExtreme && m_heightRemaining)
+        *m_heightRemaining = m_renderer->logicalBottomForFloat(floatingObject) - m_lowValue;
 
-    if (FloatTypeValue == FloatingObject::FloatRight
-        && m_renderer->logicalLeftForFloat(r) < m_offset) {
-        m_offset = m_renderer->logicalLeftForFloat(r);
-        if (m_heightRemaining)
-            *m_heightRemaining = m_renderer->logicalBottomForFloat(r) - m_lowValue;
-    }
-
-    m_last = r;
+    m_last = floatingObject;
 }
 
 LayoutUnit RenderBlock::textIndentOffset() const
@@ -4748,7 +4769,7 @@
     if (!everHadLayout())
         return;
     if (childrenInline()) {
-        setNeedsLayout(true);
+        setNeedsLayout();
         return;
     }
     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
@@ -4765,7 +4786,7 @@
         return;
 
     MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
-    setChildNeedsLayout(true, markParents);
+    setChildNeedsLayout(markParents);
 
     if (floatToRemove)
         removeFloatingObject(floatToRemove);
@@ -4863,7 +4884,7 @@
                 // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
                 // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
                 if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
-                    child->setChildNeedsLayout(true, MarkOnlyThis);
+                    child->setChildNeedsLayout(MarkOnlyThis);
                 return newLogicalTop - logicalTop;
             }
 
@@ -7552,7 +7573,7 @@
             // When the child shifts to clear an item, its width can
             // change (because it has more available line width).
             // So go ahead and mark the item as dirty.
-            child->setChildNeedsLayout(true, MarkOnlyThis);
+            child->setChildNeedsLayout(MarkOnlyThis);
         }
 
         if (childRenderBlock) {
diff --git a/Source/core/rendering/RenderBlock.h b/Source/core/rendering/RenderBlock.h
index c440d3f..06300e8 100644
--- a/Source/core/rendering/RenderBlock.h
+++ b/Source/core/rendering/RenderBlock.h
@@ -881,6 +881,9 @@
     void paintSelection(PaintInfo&, const LayoutPoint&);
     void paintCaret(PaintInfo&, const LayoutPoint&, CaretType);
 
+    bool hasCaret() const { return hasCaret(CursorCaret) || hasCaret(DragCaret); }
+    bool hasCaret(CaretType) const;
+
     FloatingObject* insertFloatingObject(RenderBox*);
     void removeFloatingObject(RenderBox*);
     void removeFloatingObjectsBelow(FloatingObject*, int logicalOffset);
@@ -1188,6 +1191,8 @@
         const FloatingObject* lastFloat() const { return m_last; }
 
     private:
+        bool updateOffsetIfNeeded(const FloatingObject*) const;
+
         const RenderBlock* m_renderer;
         int m_lowValue;
         int m_highValue;
diff --git a/Source/core/rendering/RenderBlockLineLayout.cpp b/Source/core/rendering/RenderBlockLineLayout.cpp
index 4c399db..f16fcb6 100644
--- a/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -1509,7 +1509,7 @@
     // determineStartPosition can change the fullLayout flag we have to do this here. Failure to call
     // determineStartPosition first will break fast/repaint/line-flow-with-floats-9.html.
     if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) {
-        setNeedsLayout(true, MarkOnlyThis); // Mark as needing a full layout to force us to repaint.
+        setNeedsLayout(MarkOnlyThis); // Mark as needing a full layout to force us to repaint.
         RenderView* v = view();
         if (v && !v->doingFullRepaint() && hasLayer()) {
             // Because we waited until we were already inside layout to discover
@@ -2091,7 +2091,7 @@
                 RenderBox* box = toRenderBox(o);
 
                 if (relayoutChildren || box->hasRelativeDimensions())
-                    o->setChildNeedsLayout(true, MarkOnlyThis);
+                    o->setChildNeedsLayout(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.
                 if (relayoutChildren && box->needsPreferredWidthsRecalculation())
@@ -2114,7 +2114,7 @@
                     toRenderInline(o)->updateAlwaysCreateLineBoxes(layoutState.isFullLayout());
                 if (layoutState.isFullLayout() || o->selfNeedsLayout())
                     dirtyLineBoxesForRenderer(o, layoutState.isFullLayout());
-                o->setNeedsLayout(false);
+                o->clearNeedsLayout();
             }
         }
 
@@ -3315,8 +3315,8 @@
         endPadding = 1;
     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
         addLayoutOverflow(curr->paddedLayoutOverflowRect(endPadding));
-        if (!hasOverflowClip())
-            addVisualOverflow(curr->visualOverflowRect(curr->lineTop(), curr->lineBottom()));
+        LayoutRect visualOverflow = curr->visualOverflowRect(curr->lineTop(), curr->lineBottom());
+        addContentsVisualOverflow(visualOverflow);
     }
 }
 
@@ -3426,7 +3426,7 @@
             RenderBox* o = f->m_renderer;
             setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
             if (o->isRenderBlock())
-                toRenderBlock(o)->setChildNeedsLayout(true, MarkOnlyThis);
+                toRenderBlock(o)->setChildNeedsLayout(MarkOnlyThis);
             o->layoutIfNeeded();
             // Save the old logical top before calling removePlacedObject which will set
             // isPlaced to false. Otherwise it will trigger an assert in logicalTopForFloat.
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index 30f81ff..bb53fd5 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -219,7 +219,7 @@
             if (oldStyle->position() == StaticPosition)
                 repaint();
             else if (newStyle->hasOutOfFlowPosition())
-                parent()->setChildNeedsLayout(true);
+                parent()->setChildNeedsLayout();
             if (isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
                 removeFloatingOrPositionedChildFromBlockLists();
         }
@@ -247,7 +247,7 @@
         // to determine the new static position.
         if (isOutOfFlowPositioned() && newStyle->hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle->marginBefore()
             && parent() && !parent()->normalChildNeedsLayout())
-            parent()->setChildNeedsLayout(true);
+            parent()->setChildNeedsLayout();
     }
 
     if (RenderBlock::hasPercentHeightContainerMap() && firstChild()
@@ -388,7 +388,7 @@
 
     RenderObject* child = firstChild();
     if (!child) {
-        setNeedsLayout(false);
+        clearNeedsLayout();
         return;
     }
 
@@ -400,7 +400,7 @@
     }
     statePusher.pop();
     invalidateBackgroundObscurationStatus();
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 // More IE extensions.  clientWidth and clientHeight represent the interior of an object
@@ -1517,7 +1517,7 @@
     return false;
 }
 
-bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
+bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset, ContentsClipBehavior contentsClipBehavior)
 {
     if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
         return false;
@@ -1528,6 +1528,27 @@
     if (!isControlClip && !isOverflowClip)
         return false;
 
+    LayoutRect clipRect = isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, paintInfo.renderRegion);
+    RoundedRect clipRoundedRect(0, 0, 0, 0);
+    bool hasBorderRadius = style()->hasBorderRadius();
+    if (hasBorderRadius)
+        clipRoundedRect = style()->getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size()));
+
+    if (contentsClipBehavior == SkipContentsClipIfPossible) {
+        LayoutRect contentsVisualOverflow = contentsVisualOverflowRect();
+        if (contentsVisualOverflow.isEmpty())
+            return false;
+
+        LayoutRect conservativeClipRect = clipRect;
+        if (hasBorderRadius)
+            conservativeClipRect.intersect(clipRoundedRect.radiusCenterRect());
+        conservativeClipRect.moveBy(-accumulatedOffset);
+        if (hasLayer())
+            conservativeClipRect.move(scrolledContentOffset());
+        if (conservativeClipRect.contains(contentsVisualOverflow))
+            return false;
+    }
+
     if (paintInfo.phase == PaintPhaseOutline)
         paintInfo.phase = PaintPhaseChildOutlines;
     else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
@@ -1535,11 +1556,10 @@
         paintObject(paintInfo, accumulatedOffset);
         paintInfo.phase = PaintPhaseChildBlockBackgrounds;
     }
-    IntRect clipRect = pixelSnappedIntRect(isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, paintInfo.renderRegion));
     paintInfo.context->save();
-    if (style()->hasBorderRadius())
-        paintInfo.context->clipRoundedRect(style()->getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())));
-    paintInfo.context->clip(clipRect);
+    if (hasBorderRadius)
+        paintInfo.context->clipRoundedRect(clipRoundedRect);
+    paintInfo.context->clip(pixelSnappedIntRect(clipRect));
     return true;
 }
 
@@ -1858,7 +1878,7 @@
             RootInlineBox* root = box->root();
             root->block()->setStaticInlinePositionForChild(this, root->lineTopWithLeading(), LayoutUnit::fromFloatRound(box->logicalLeft()));
             if (style()->hasStaticInlinePosition(box->isHorizontal()))
-                setChildNeedsLayout(true, MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
+                setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
         } else {
             // Our object was a block originally, so we make our normal flow position be
             // just below the line box (as though all the inlines that came before us got
@@ -1866,7 +1886,7 @@
             // in flow).  This value was cached in the y() of the box.
             layer()->setStaticBlockPosition(box->logicalTop());
             if (style()->hasStaticBlockPosition(box->isHorizontal()))
-                setChildNeedsLayout(true, MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
+                setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
         }
 
         // Nuke the box.
@@ -4210,7 +4230,8 @@
     }
 
     // Add in the final overflow with shadows and outsets combined.
-    addVisualOverflow(LayoutRect(overflowMinX, overflowMinY, overflowMaxX - overflowMinX, overflowMaxY - overflowMinY));
+    LayoutRect visualEffectOverflow(overflowMinX, overflowMinY, overflowMaxX - overflowMinX, overflowMaxY - overflowMinY);
+    addVisualOverflow(visualEffectOverflow);
 }
 
 void RenderBox::addOverflowFromChild(RenderBox* child, const LayoutSize& delta)
@@ -4229,11 +4250,11 @@
     // Add in visual overflow from the child.  Even if the child clips its overflow, it may still
     // have visual overflow of its own set from box shadows or reflections.  It is unnecessary to propagate this
     // overflow if we are clipping our own overflow.
-    if (child->hasSelfPaintingLayer() || hasOverflowClip())
+    if (child->hasSelfPaintingLayer())
         return;
     LayoutRect childVisualOverflowRect = child->visualOverflowRectForPropagation(style());
     childVisualOverflowRect.move(delta);
-    addVisualOverflow(childVisualOverflowRect);
+    addContentsVisualOverflow(childVisualOverflowRect);
 }
 
 void RenderBox::addLayoutOverflow(const LayoutRect& rect)
@@ -4298,12 +4319,24 @@
     m_overflow->addVisualOverflow(rect);
 }
 
+void RenderBox::addContentsVisualOverflow(const LayoutRect& rect)
+{
+    if (!hasOverflowClip()) {
+        addVisualOverflow(rect);
+        return;
+    }
+
+    if (!m_overflow)
+        m_overflow = adoptPtr(new RenderOverflow(clientBoxRect(), borderBoxRect()));
+    m_overflow->addContentsVisualOverflow(rect);
+}
+
 void RenderBox::clearLayoutOverflow()
 {
     if (!m_overflow)
         return;
 
-    if (!hasVisualOverflow()) {
+    if (!hasVisualOverflow() && contentsVisualOverflowRect().isEmpty()) {
         m_overflow.clear();
         return;
     }
diff --git a/Source/core/rendering/RenderBox.h b/Source/core/rendering/RenderBox.h
index 24562dc..4246b71 100644
--- a/Source/core/rendering/RenderBox.h
+++ b/Source/core/rendering/RenderBox.h
@@ -40,6 +40,8 @@
 
 enum ShouldComputePreferred { ComputeActual, ComputePreferred };
 
+enum ContentsClipBehavior { ForceContentsClip, SkipContentsClipIfPossible };
+
 class RenderBox : public RenderBoxModelObject {
 public:
     explicit RenderBox(ContainerNode*);
@@ -186,9 +188,14 @@
 
     LayoutRect overflowRectForPaintRejection() const;
 
+    LayoutRect contentsVisualOverflowRect() const { return m_overflow ? m_overflow->contentsVisualOverflowRect() : LayoutRect(); }
+
     void addLayoutOverflow(const LayoutRect&);
     void addVisualOverflow(const LayoutRect&);
 
+    // Clipped by the contents clip, if one exists.
+    void addContentsVisualOverflow(const LayoutRect&);
+
     void addVisualEffectOverflow();
     void addOverflowFromChild(RenderBox* child) { addOverflowFromChild(child, child->locationOffset()); }
     void addOverflowFromChild(RenderBox* child, const LayoutSize& delta);
@@ -470,7 +477,7 @@
     LayoutRect clipRect(const LayoutPoint& location, RenderRegion*);
     virtual bool hasControlClip() const { return false; }
     virtual LayoutRect controlClipRect(const LayoutPoint&) const { return LayoutRect(); }
-    bool pushContentsClip(PaintInfo&, const LayoutPoint& accumulatedOffset);
+    bool pushContentsClip(PaintInfo&, const LayoutPoint& accumulatedOffset, ContentsClipBehavior);
     void popContentsClip(PaintInfo&, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset);
 
     virtual void paintObject(PaintInfo&, const LayoutPoint&) { ASSERT_NOT_REACHED(); }
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
index 8135893..bdf05c9 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
@@ -333,7 +333,7 @@
     // Repaint with our new bounds if they are different from our old bounds.
     repainter.repaintAfterLayout();
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 // The first walk over our kids is to find out if we have any flexible children.
@@ -346,7 +346,7 @@
             // may have changed, and we need to reallocate space.
             child->clearOverrideSize();
             if (!relayoutChildren)
-                child->setChildNeedsLayout(true, MarkOnlyThis);
+                child->setChildNeedsLayout(MarkOnlyThis);
             haveFlex = true;
             unsigned int flexGroup = child->style()->boxFlexGroup();
             if (lowestFlexGroup == 0)
@@ -393,7 +393,7 @@
         for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
             // make sure we relayout children if we need it.
             if (relayoutChildren || (child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent())))
-                child->setChildNeedsLayout(true, MarkOnlyThis);
+                child->setChildNeedsLayout(MarkOnlyThis);
 
             if (child->isOutOfFlowPositioned())
                 continue;
@@ -450,7 +450,7 @@
                 if (childLayer->staticBlockPosition() != yPos) {
                     childLayer->setStaticBlockPosition(yPos);
                     if (child->style()->hasStaticBlockPosition(style()->isHorizontalWritingMode()))
-                        child->setChildNeedsLayout(true, MarkOnlyThis);
+                        child->setChildNeedsLayout(MarkOnlyThis);
                 }
                 continue;
             }
@@ -469,7 +469,7 @@
             LayoutUnit oldChildHeight = child->height();
             child->updateLogicalHeight();
             if (oldChildHeight != child->height())
-                child->setChildNeedsLayout(true, MarkOnlyThis);
+                child->setChildNeedsLayout(MarkOnlyThis);
 
             if (!child->needsLayout())
                 child->markForPaginationRelayoutIfNeeded();
@@ -682,7 +682,7 @@
         for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
             // Make sure we relayout children if we need it.
             if (!haveLineClamp && (relayoutChildren || (child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent()))))
-                child->setChildNeedsLayout(true, MarkOnlyThis);
+                child->setChildNeedsLayout(MarkOnlyThis);
 
             if (child->isOutOfFlowPositioned()) {
                 child->containingBlock()->insertPositionedObject(child);
@@ -691,7 +691,7 @@
                 if (childLayer->staticBlockPosition() != height()) {
                     childLayer->setStaticBlockPosition(height());
                     if (child->style()->hasStaticBlockPosition(style()->isHorizontalWritingMode()))
-                        child->setChildNeedsLayout(true, MarkOnlyThis);
+                        child->setChildNeedsLayout(MarkOnlyThis);
                 }
                 continue;
             }
@@ -909,7 +909,7 @@
         child->clearOverrideSize();
         if (relayoutChildren || (child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent()))
             || (child->style()->height().isAuto() && child->isBlockFlow())) {
-            child->setChildNeedsLayout(true, MarkOnlyThis);
+            child->setChildNeedsLayout(MarkOnlyThis);
 
             // Dirty all the positioned objects.
             if (child->isRenderBlock()) {
@@ -1007,7 +1007,7 @@
         child->clearOverrideSize();
         if ((child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent()))
             || (child->style()->height().isAuto() && child->isBlockFlow())) {
-            child->setChildNeedsLayout(true);
+            child->setChildNeedsLayout();
 
             if (child->isRenderBlock()) {
                 toRenderBlock(child)->markPositionedObjectsForLayout();
diff --git a/Source/core/rendering/RenderEmbeddedObject.cpp b/Source/core/rendering/RenderEmbeddedObject.cpp
index de41af3..475acd6 100644
--- a/Source/core/rendering/RenderEmbeddedObject.cpp
+++ b/Source/core/rendering/RenderEmbeddedObject.cpp
@@ -225,7 +225,7 @@
     if (!widget() && frameView())
         frameView()->addWidgetToUpdate(this);
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 
     if (!canHaveChildren())
         return;
@@ -254,7 +254,7 @@
     childBox->style()->setHeight(Length(newSize.height(), Fixed));
     childBox->style()->setWidth(Length(newSize.width(), Fixed));
     childBox->forceLayout();
-    setChildNeedsLayout(false);
+    clearNeedsLayout();
 
     statePusher.pop();
 }
diff --git a/Source/core/rendering/RenderFieldset.cpp b/Source/core/rendering/RenderFieldset.cpp
index 291c686..7587425 100644
--- a/Source/core/rendering/RenderFieldset.cpp
+++ b/Source/core/rendering/RenderFieldset.cpp
@@ -65,7 +65,7 @@
     RenderBox* legend = findLegend();
     if (legend) {
         if (relayoutChildren)
-            legend->setNeedsLayout(true);
+            legend->setNeedsLayout();
         legend->layoutIfNeeded();
 
         LayoutUnit logicalLeft;
diff --git a/Source/core/rendering/RenderFlexibleBox.cpp b/Source/core/rendering/RenderFlexibleBox.cpp
index 40c26e0..54139ab 100644
--- a/Source/core/rendering/RenderFlexibleBox.cpp
+++ b/Source/core/rendering/RenderFlexibleBox.cpp
@@ -228,7 +228,7 @@
         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
             EAlignItems previousAlignment = resolveAlignment(oldStyle, child->style());
             if (previousAlignment == AlignStretch && previousAlignment != resolveAlignment(style(), child->style()))
-                child->setChildNeedsLayout(true, MarkOnlyThis);
+                child->setChildNeedsLayout(MarkOnlyThis);
         }
     }
 }
@@ -294,7 +294,7 @@
 
     repainter.repaintAfterLayout();
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderFlexibleBox::appendChildFrameRects(ChildFrameRects& childFrameRects)
@@ -659,7 +659,7 @@
     if (flexBasis.isAuto() || (flexBasis.isFixed() && !flexBasis.value() && hasInfiniteLineLength)) {
         if (hasOrthogonalFlow(child)) {
             if (hasOverrideSize)
-                child->setChildNeedsLayout(true, MarkOnlyThis);
+                child->setChildNeedsLayout(MarkOnlyThis);
             child->layoutIfNeeded();
         }
         LayoutUnit mainAxisExtent = hasOrthogonalFlow(child) ? child->logicalHeight() : child->maxPreferredLogicalWidth();
@@ -1027,7 +1027,7 @@
     if (childLayer->staticBlockPosition() != staticBlockPosition) {
         childLayer->setStaticBlockPosition(staticBlockPosition);
         if (child->style()->hasStaticBlockPosition(style()->isHorizontalWritingMode()))
-            child->setChildNeedsLayout(true, MarkOnlyThis);
+            child->setChildNeedsLayout(MarkOnlyThis);
     }
 }
 
@@ -1101,7 +1101,7 @@
         setLogicalOverrideSize(child, childPreferredSize);
         // FIXME: Can avoid laying out here in some cases. See https://webkit.org/b/87905.
         if (needToStretchChild(child) || childPreferredSize != mainAxisExtentForChild(child))
-            child->setChildNeedsLayout(true, MarkOnlyThis);
+            child->setChildNeedsLayout(MarkOnlyThis);
         else {
             // To avoid double applying margin changes in updateAutoMarginsInCrossAxis, we reset the margins here.
             resetAutoMarginsAndLogicalTopInCrossAxis(child);
diff --git a/Source/core/rendering/RenderFlowThread.cpp b/Source/core/rendering/RenderFlowThread.cpp
index a6b3ae8..97ef84a 100644
--- a/Source/core/rendering/RenderFlowThread.cpp
+++ b/Source/core/rendering/RenderFlowThread.cpp
@@ -84,7 +84,7 @@
     RenderBlock::styleDidChange(diff, oldStyle);
 
     if (oldStyle && oldStyle->writingMode() != style()->writingMode())
-        m_regionsInvalidated = true;
+        invalidateRegions();
 }
 
 void RenderFlowThread::removeFlowChildInfo(RenderObject* child)
@@ -117,7 +117,7 @@
     m_regionRangeMap.clear();
     m_breakBeforeToRegionMap.clear();
     m_breakAfterToRegionMap.clear();
-    setNeedsLayout(true);
+    setNeedsLayout();
 
     m_regionsInvalidated = true;
 }
@@ -849,7 +849,7 @@
 
         // FIXME: We need to find a way to avoid marking all the regions ancestors for layout
         // as we are already inside layout.
-        region->setNeedsLayout(true);
+        region->setNeedsLayout();
     }
 }
 
diff --git a/Source/core/rendering/RenderFlowThread.h b/Source/core/rendering/RenderFlowThread.h
index 18fb7db..3da1907 100644
--- a/Source/core/rendering/RenderFlowThread.h
+++ b/Source/core/rendering/RenderFlowThread.h
@@ -87,6 +87,7 @@
     // Check if the content is flown into at least a region with region styling rules.
     bool hasRegionsWithStyling() const { return m_hasRegionsWithStyling; }
     void checkRegionsWithStyling();
+    virtual void regionChangedWritingMode(RenderRegion*) { }
 
     void validateRegions();
     void invalidateRegions();
diff --git a/Source/core/rendering/RenderFrameSet.cpp b/Source/core/rendering/RenderFrameSet.cpp
index 5849e14..0126642 100644
--- a/Source/core/rendering/RenderFrameSet.cpp
+++ b/Source/core/rendering/RenderFrameSet.cpp
@@ -480,7 +480,7 @@
             repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds));
     }
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderFrameSet::positionFrames()
@@ -505,7 +505,7 @@
             if (width != child->width() || height != child->height()) {
                 child->setWidth(width);
                 child->setHeight(height);
-                child->setNeedsLayout(true);
+                child->setNeedsLayout();
                 child->layout();
             }
 
@@ -522,7 +522,7 @@
     for (; child; child = child->nextSiblingBox()) {
         child->setWidth(0);
         child->setHeight(0);
-        child->setNeedsLayout(false);
+        child->clearNeedsLayout();
     }
 }
 
@@ -549,7 +549,7 @@
         return;
     axis.m_deltas[axis.m_splitBeingResized - 1] += delta;
     axis.m_deltas[axis.m_splitBeingResized] -= delta;
-    setNeedsLayout(true);
+    setNeedsLayout();
 }
 
 bool RenderFrameSet::userResize(MouseEvent* evt)
diff --git a/Source/core/rendering/RenderGrid.cpp b/Source/core/rendering/RenderGrid.cpp
index 3a9e0a7..9d0d589 100644
--- a/Source/core/rendering/RenderGrid.cpp
+++ b/Source/core/rendering/RenderGrid.cpp
@@ -273,7 +273,7 @@
 
     repainter.repaintAfterLayout();
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderGrid::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
@@ -514,7 +514,7 @@
     // doesn't return if the logical height is available so would need to be changed.
     // 2) Relayout if the column track's used breadth changed OR the logical height is unavailable.
     if (!child->needsLayout())
-        child->setNeedsLayout(true, MarkOnlyThis);
+        child->setNeedsLayout(MarkOnlyThis);
 
     child->setOverrideContainingBlockContentLogicalWidth(gridAreaBreadthForChild(child, ForColumns, columnTracks));
     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
@@ -855,7 +855,7 @@
         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, rowTracks);
         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight)
-            child->setNeedsLayout(true, MarkOnlyThis);
+            child->setNeedsLayout(MarkOnlyThis);
 
         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
@@ -975,7 +975,6 @@
 
 size_t RenderGrid::resolveGridPositionFromStyle(const GridPosition& position, GridPositionSide side) const
 {
-    // FIXME: Handle other values for grid-{row,column} like ranges or line names.
     switch (position.type()) {
     case ExplicitPosition: {
         ASSERT(position.integerPosition());
@@ -997,8 +996,24 @@
         return adjustGridPositionForSide(endOfTrack - resolvedPosition, side);
     }
     case NamedGridAreaPosition:
-        // FIXME: Support resolving named grid area (crbug.com/258092).
+    {
+        NamedGridAreaMap::const_iterator it = style()->namedGridArea().find(position.namedGridLine());
+        // Unknown grid area should have been computed to 'auto' by now.
+        ASSERT(it != style()->namedGridArea().end());
+        const GridCoordinate& gridAreaCoordinate = it->value;
+        switch (side) {
+        case ColumnStartSide:
+            return gridAreaCoordinate.columns.initialPositionIndex;
+        case ColumnEndSide:
+            return gridAreaCoordinate.columns.finalPositionIndex;
+        case RowStartSide:
+            return gridAreaCoordinate.rows.initialPositionIndex;
+        case RowEndSide:
+            return gridAreaCoordinate.rows.finalPositionIndex;
+        }
+        ASSERT_NOT_REACHED();
         return 0;
+    }
     case AutoPosition:
     case SpanPosition:
         // 'auto' and span depend on the opposite position for resolution (e.g. grid-row: auto / 1 or grid-column: span 3 / "myHeader").
diff --git a/Source/core/rendering/RenderHTMLCanvas.cpp b/Source/core/rendering/RenderHTMLCanvas.cpp
index d75685a..e1c5924 100644
--- a/Source/core/rendering/RenderHTMLCanvas.cpp
+++ b/Source/core/rendering/RenderHTMLCanvas.cpp
@@ -92,7 +92,7 @@
         return;
 
     if (!selfNeedsLayout())
-        setNeedsLayout(true);
+        setNeedsLayout();
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderIFrame.cpp b/Source/core/rendering/RenderIFrame.cpp
index a4b649a..d594e8b 100644
--- a/Source/core/rendering/RenderIFrame.cpp
+++ b/Source/core/rendering/RenderIFrame.cpp
@@ -137,7 +137,7 @@
     addVisualEffectOverflow();
     updateLayerTransform();
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 }
diff --git a/Source/core/rendering/RenderImage.cpp b/Source/core/rendering/RenderImage.cpp
index d1ac1ea..ce48656 100644
--- a/Source/core/rendering/RenderImage.cpp
+++ b/Source/core/rendering/RenderImage.cpp
@@ -34,7 +34,7 @@
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLMapElement.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/graphics/Font.h"
@@ -91,7 +91,7 @@
 static const float maxAltTextWidth = 1024;
 static const int maxAltTextHeight = 256;
 
-IntSize RenderImage::imageSizeForError(CachedImage* newImage) const
+IntSize RenderImage::imageSizeForError(ImageResource* newImage) const
 {
     ASSERT_ARG(newImage, newImage);
     ASSERT_ARG(newImage, newImage->imageForRenderer(this));
@@ -112,7 +112,7 @@
 
 // Sets the image height and width to fit the alt text.  Returns true if the
 // image size changed.
-bool RenderImage::setImageSizeForAltText(CachedImage* newImage /* = 0 */)
+bool RenderImage::setImageSizeForAltText(ImageResource* newImage /* = 0 */)
 {
     IntSize imageSize;
     if (newImage && newImage->imageForRenderer(this))
@@ -234,7 +234,7 @@
         if (imageSizeChanged || hasOverrideSize || containingBlockNeedsToRecomputePreferredSize) {
             shouldRepaint = false;
             if (!selfNeedsLayout())
-                setNeedsLayout(true);
+                setNeedsLayout();
         }
     }
 
@@ -585,7 +585,7 @@
     if (!m_imageResource)
         return 0;
 
-    CachedImage* cachedImage = m_imageResource->cachedImage();
+    ImageResource* cachedImage = m_imageResource->cachedImage();
     if (cachedImage && cachedImage->image() && cachedImage->image()->isSVGImage())
         return static_cast<SVGImage*>(cachedImage->image())->embeddedContentBox();
 
diff --git a/Source/core/rendering/RenderImage.h b/Source/core/rendering/RenderImage.h
index 9903965..6c4aeed 100644
--- a/Source/core/rendering/RenderImage.h
+++ b/Source/core/rendering/RenderImage.h
@@ -44,9 +44,9 @@
 
     RenderImageResource* imageResource() { return m_imageResource.get(); }
     const RenderImageResource* imageResource() const { return m_imageResource.get(); }
-    CachedImage* cachedImage() const { return m_imageResource ? m_imageResource->cachedImage() : 0; }
+    ImageResource* cachedImage() const { return m_imageResource ? m_imageResource->cachedImage() : 0; }
 
-    bool setImageSizeForAltText(CachedImage* newImage = 0);
+    bool setImageSizeForAltText(ImageResource* newImage = 0);
 
     void updateAltText();
 
@@ -98,7 +98,7 @@
 
     virtual bool boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance, InlineFlowBox*) const OVERRIDE FINAL;
 
-    IntSize imageSizeForError(CachedImage*) const;
+    IntSize imageSizeForError(ImageResource*) const;
     void imageDimensionsChanged(bool imageSizeChanged, const IntRect* = 0);
     bool updateIntrinsicSizeIfNeeded(const LayoutSize&, bool imageSizeChanged);
 
diff --git a/Source/core/rendering/RenderImageResource.cpp b/Source/core/rendering/RenderImageResource.cpp
index 9ac02de..4a38fdd 100644
--- a/Source/core/rendering/RenderImageResource.cpp
+++ b/Source/core/rendering/RenderImageResource.cpp
@@ -28,7 +28,7 @@
 #include "config.h"
 #include "core/rendering/RenderImageResource.h"
 
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/platform/graphics/Image.h"
 #include "core/rendering/RenderObject.h"
 
@@ -59,7 +59,7 @@
         m_cachedImage->removeClient(m_renderer);
 }
 
-void RenderImageResource::setCachedImage(CachedImage* newImage)
+void RenderImageResource::setImageResource(ImageResource* newImage)
 {
     ASSERT(m_renderer);
 
diff --git a/Source/core/rendering/RenderImageResource.h b/Source/core/rendering/RenderImageResource.h
index b07dc78..d222111 100644
--- a/Source/core/rendering/RenderImageResource.h
+++ b/Source/core/rendering/RenderImageResource.h
@@ -26,7 +26,7 @@
 #ifndef RenderImageResource_h
 #define RenderImageResource_h
 
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/graphics/Image.h"
 #include "core/platform/graphics/LayoutSize.h"
@@ -49,8 +49,8 @@
     virtual void initialize(RenderObject*);
     virtual void shutdown();
 
-    void setCachedImage(CachedImage*);
-    CachedImage* cachedImage() const { return m_cachedImage.get(); }
+    void setImageResource(ImageResource*);
+    ImageResource* cachedImage() const { return m_cachedImage.get(); }
     virtual bool hasImage() const { return m_cachedImage; }
 
     void resetAnimation();
@@ -70,7 +70,7 @@
 protected:
     RenderImageResource();
     RenderObject* m_renderer;
-    ResourcePtr<CachedImage> m_cachedImage;
+    ResourcePtr<ImageResource> m_cachedImage;
 
 private:
     static Image* nullImage();
diff --git a/Source/core/rendering/RenderImageResourceStyleImage.cpp b/Source/core/rendering/RenderImageResourceStyleImage.cpp
index 4580e15..ec90235 100644
--- a/Source/core/rendering/RenderImageResourceStyleImage.cpp
+++ b/Source/core/rendering/RenderImageResourceStyleImage.cpp
@@ -28,9 +28,9 @@
 #include "config.h"
 #include "core/rendering/RenderImageResourceStyleImage.h"
 
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/RenderObject.h"
-#include "core/rendering/style/StyleCachedImage.h"
+#include "core/rendering/style/StyleFetchedImage.h"
 
 namespace WebCore {
 
@@ -48,8 +48,8 @@
 {
     RenderImageResource::initialize(renderer);
 
-    if (m_styleImage->isCachedImage())
-        m_cachedImage = static_cast<StyleCachedImage*>(m_styleImage.get())->cachedImage();
+    if (m_styleImage->isImageResource())
+        m_cachedImage = static_cast<StyleFetchedImage*>(m_styleImage.get())->cachedImage();
 
     m_styleImage->addClient(m_renderer);
 }
diff --git a/Source/core/rendering/RenderInline.cpp b/Source/core/rendering/RenderInline.cpp
index 9aa9940..9464e2a 100644
--- a/Source/core/rendering/RenderInline.cpp
+++ b/Source/core/rendering/RenderInline.cpp
@@ -192,7 +192,7 @@
         bool alwaysCreateLineBoxes = hasSelfPaintingLayer() || hasBoxDecorations() || newStyle->hasPadding() || newStyle->hasMargin() || hasOutline();
         if (oldStyle && alwaysCreateLineBoxes) {
             dirtyLineBoxes(false);
-            setNeedsLayout(true);
+            setNeedsLayout();
         }
         m_alwaysCreateLineBoxes = alwaysCreateLineBoxes;
     }
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index 33efe07..9f6939f 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -2530,7 +2530,7 @@
 bool RenderLayer::isActive() const
 {
     Page* page = renderer()->frame()->page();
-    return page && page->focusController()->isActive();
+    return page && page->focusController().isActive();
 }
 
 static int cornerStart(const RenderStyle* style, int minX, int maxX, int thickness)
@@ -3056,7 +3056,7 @@
             if (!m_inOverflowRelayout) {
                 // Our proprietary overflow: overlay value doesn't trigger a layout.
                 m_inOverflowRelayout = true;
-                renderer()->setNeedsLayout(true, MarkOnlyThis);
+                renderer()->setNeedsLayout(MarkOnlyThis);
                 if (renderer()->isRenderBlock()) {
                     RenderBlock* block = toRenderBlock(renderer());
                     block->scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
@@ -6310,6 +6310,33 @@
         renderer()->repaint();
 }
 
+void RenderLayer::addLayerHitTestRects(LayerHitTestRects& rects) const
+{
+    if (!size().isEmpty()) {
+        Vector<LayoutRect> rect;
+
+        if (renderBox() && renderBox()->scrollsOverflow()) {
+            // For scrolling layers, rects are taken to be in the space of the contents.
+            // We need to include both the entire contents, and also the bounding box
+            // of the layer in the space of it's parent (eg. for border / scroll bars).
+            rect.append(m_overflowRect);
+            rects.set(this, rect);
+            if (const RenderLayer* parentLayer = parent()) {
+                LayerHitTestRects::iterator iter = rects.find(parentLayer);
+                if (iter == rects.end())
+                    iter = rects.add(parentLayer, Vector<LayoutRect>()).iterator;
+                iter->value.append(boundingBox(parentLayer));
+            }
+        } else {
+            rect.append(localBoundingBox());
+            rects.set(this, rect);
+        }
+    }
+
+    for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
+        child->addLayerHitTestRects(rects);
+}
+
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/RenderLayer.h b/Source/core/rendering/RenderLayer.h
index db8fd09..5a7c14f 100644
--- a/Source/core/rendering/RenderLayer.h
+++ b/Source/core/rendering/RenderLayer.h
@@ -811,6 +811,8 @@
 
     void setForceNeedsCompositedScrolling(ForceNeedsCompositedScrollingMode);
 
+    void addLayerHitTestRects(LayerHitTestRects&) const;
+
 private:
     enum CollectLayersBehavior {
         ForceLayerToStackingContainer,
diff --git a/Source/core/rendering/RenderLayerBacking.cpp b/Source/core/rendering/RenderLayerBacking.cpp
index 938cf70..c8991f2 100644
--- a/Source/core/rendering/RenderLayerBacking.cpp
+++ b/Source/core/rendering/RenderLayerBacking.cpp
@@ -34,7 +34,7 @@
 #include "core/html/HTMLMediaElement.h"
 #include "core/html/canvas/CanvasRenderingContext.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/Chrome.h"
 #include "core/page/FrameView.h"
 #include "core/page/Settings.h"
@@ -1344,7 +1344,7 @@
         return false;
 
     RenderImage* imageRenderer = toRenderImage(renderObject);
-    if (CachedImage* cachedImage = imageRenderer->cachedImage()) {
+    if (ImageResource* cachedImage = imageRenderer->cachedImage()) {
         if (!cachedImage->hasImage())
             return false;
 
@@ -1382,7 +1382,7 @@
     ASSERT(renderer()->isImage());
     RenderImage* imageRenderer = toRenderImage(renderer());
 
-    CachedImage* cachedImage = imageRenderer->cachedImage();
+    ImageResource* cachedImage = imageRenderer->cachedImage();
     if (!cachedImage)
         return;
 
diff --git a/Source/core/rendering/RenderLayerCompositor.cpp b/Source/core/rendering/RenderLayerCompositor.cpp
index 7073a4b..c8ea29d 100644
--- a/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/RenderLayerCompositor.cpp
@@ -471,9 +471,6 @@
 
 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer* renderLayer)
 {
-    // Inform the inspector that the given RenderLayer was destroyed.
-    InspectorInstrumentation::renderLayerDestroyed(page(), renderLayer);
-
     ASSERT(m_compositedLayerCount > 0);
     --m_compositedLayerCount;
 }
@@ -784,6 +781,14 @@
 
     // First accumulate the straightforward compositing reasons.
     CompositingReasons directReasons = directReasonsForCompositing(layer);
+
+    // Video is special. It's the only RenderLayer type that can both have
+    // RenderLayer children and whose children can't use its backing to render
+    // into. These children (the controls) always need to be promoted into their
+    // own layers to draw on top of the accelerated video.
+    if (compositingState.m_compositingAncestor && compositingState.m_compositingAncestor->renderer()->isVideo())
+        directReasons |= CompositingReasonLayerForVideoOverlay;
+
     if (canBeComposited(layer)) {
         reasonsToComposite |= directReasons;
         reasonsToComposite |= (inCompositingMode() && layer->isRootLayer()) ? CompositingReasonRoot : CompositingReasonNone;
@@ -808,13 +813,6 @@
         overlapCompositingReason = overlapMap->overlapsLayers(absBounds) ? CompositingReasonOverlap : CompositingReasonNone;
     }
 
-    // Video is special. It's the only RenderLayer type that can both have
-    // RenderLayer children and whose children can't use its backing to render
-    // into. These children (the controls) always need to be promoted into their
-    // own layers to draw on top of the accelerated video.
-    if (compositingState.m_compositingAncestor && compositingState.m_compositingAncestor->renderer()->isVideo())
-        overlapCompositingReason = CompositingReasonOverlap;
-
     reasonsToComposite |= overlapCompositingReason;
 
     // The children of this layer don't need to composite, unless there is
diff --git a/Source/core/rendering/RenderLayerFilterInfo.cpp b/Source/core/rendering/RenderLayerFilterInfo.cpp
index e10ff88..abad09d 100644
--- a/Source/core/rendering/RenderLayerFilterInfo.cpp
+++ b/Source/core/rendering/RenderLayerFilterInfo.cpp
@@ -31,8 +31,8 @@
 
 #include "core/rendering/RenderLayerFilterInfo.h"
 
-#include "core/loader/cache/CachedDocument.h"
-#include "core/loader/cache/CachedSVGDocumentReference.h"
+#include "core/loader/cache/DocumentResource.h"
+#include "core/loader/cache/DocumentResourceReference.h"
 #include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
 #include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
 #include "core/rendering/FilterEffectRenderer.h"
@@ -119,8 +119,8 @@
         if (filterOperation->getOperationType() != FilterOperation::REFERENCE)
             continue;
         ReferenceFilterOperation* referenceFilterOperation = static_cast<ReferenceFilterOperation*>(filterOperation.get());
-        CachedSVGDocumentReference* documentReference = referenceFilterOperation->cachedSVGDocumentReference();
-        CachedDocument* cachedSVGDocument = documentReference ? documentReference->document() : 0;
+        DocumentResourceReference* documentReference = referenceFilterOperation->documentResourceReference();
+        DocumentResource* cachedSVGDocument = documentReference ? documentReference->document() : 0;
 
         if (cachedSVGDocument) {
             // Reference is external; wait for notifyFinished().
diff --git a/Source/core/rendering/RenderLayerFilterInfo.h b/Source/core/rendering/RenderLayerFilterInfo.h
index f7c3a22..ad29a02 100644
--- a/Source/core/rendering/RenderLayerFilterInfo.h
+++ b/Source/core/rendering/RenderLayerFilterInfo.h
@@ -31,7 +31,7 @@
 #define RenderLayerFilterInfo_h
 
 #include "core/dom/Element.h"
-#include "core/loader/cache/CachedDocument.h"
+#include "core/loader/cache/DocumentResource.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/graphics/filters/FilterOperation.h"
 #include "core/platform/graphics/filters/custom/CustomFilterProgramClient.h"
@@ -48,7 +48,7 @@
 
 typedef HashMap<const RenderLayer*, RenderLayerFilterInfo*> RenderLayerFilterInfoMap;
 
-class RenderLayerFilterInfo : public CustomFilterProgramClient, public CachedDocumentClient {
+class RenderLayerFilterInfo : public CustomFilterProgramClient, public DocumentResourceClient {
 public:
     static RenderLayerFilterInfo* filterInfoForRenderLayer(const RenderLayer*);
     static RenderLayerFilterInfo* createFilterInfoForRenderLayerIfNeeded(RenderLayer*);
@@ -85,7 +85,7 @@
 
     static RenderLayerFilterInfoMap* s_filterMap;
     Vector<RefPtr<Element> > m_internalSVGReferences;
-    Vector<ResourcePtr<CachedDocument> > m_externalSVGReferences;
+    Vector<ResourcePtr<DocumentResource> > m_externalSVGReferences;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderLayerModelObject.cpp b/Source/core/rendering/RenderLayerModelObject.cpp
index c5aecec..e0f8f77 100644
--- a/Source/core/rendering/RenderLayerModelObject.cpp
+++ b/Source/core/rendering/RenderLayerModelObject.cpp
@@ -145,7 +145,7 @@
     if (requiresLayer()) {
         if (!layer() && layerCreationAllowedForSubtree()) {
             if (s_wasFloating && isFloating())
-                setChildNeedsLayout(true);
+                setChildNeedsLayout();
             ensureLayer();
             if (parent() && !needsLayout() && containingBlock()) {
                 layer()->setRepaintStatus(NeedsFullRepaint);
@@ -159,7 +159,7 @@
         setHasReflection(false);
         layer()->removeOnlyThisLayer(); // calls destroyLayer() which clears m_layer
         if (s_wasFloating && isFloating())
-            setChildNeedsLayout(true);
+            setChildNeedsLayout();
         if (s_hadTransform)
             setNeedsLayoutAndPrefWidthsRecalc();
     }
@@ -167,7 +167,7 @@
     if (layer()) {
         layer()->styleChanged(diff, oldStyle);
         if (s_hadLayer && layer()->isSelfPaintingLayer() != s_layerWasSelfPainting)
-            setChildNeedsLayout(true);
+            setChildNeedsLayout();
     }
 
     if (FrameView *frameView = view()->frameView()) {
@@ -184,16 +184,20 @@
 
 void RenderLayerModelObject::addLayerHitTestRects(LayerHitTestRects& rects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
 {
-    // If we have a new layer then our current layer/offset is irrelevant.
-    LayoutPoint adjustedLayerOffset = layerOffset;
-    LayoutRect adjustedContainerRect = containerRect;
     if (hasLayer()) {
-        currentLayer = layer();
-        adjustedLayerOffset = LayoutPoint();
-        adjustedContainerRect = LayoutRect();
+        if (isRenderView()) {
+            // RenderView is handled with a special fast-path, but it needs to know the current layer.
+            RenderObject::addLayerHitTestRects(rects, layer(), LayoutPoint(), LayoutRect());
+        } else {
+            // Since a RenderObject never lives outside it's container RenderLayer, we can switch
+            // to marking entire layers instead. This may sometimes mark more than necessary (when
+            // a layer is made of disjoint objects) but in practice is a significant performance
+            // savings.
+            layer()->addLayerHitTestRects(rects);
+        }
+    } else {
+        RenderObject::addLayerHitTestRects(rects, currentLayer, layerOffset, containerRect);
     }
-
-    RenderObject::addLayerHitTestRects(rects, currentLayer, adjustedLayerOffset, adjustedContainerRect);
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderLazyBlock.cpp b/Source/core/rendering/RenderLazyBlock.cpp
index 649c579..a43ab54 100644
--- a/Source/core/rendering/RenderLazyBlock.cpp
+++ b/Source/core/rendering/RenderLazyBlock.cpp
@@ -164,7 +164,7 @@
         updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
 
         if (relayoutChildren)
-            child->setNeedsLayout(true, MarkOnlyThis);
+            child->setNeedsLayout(MarkOnlyThis);
 
         if (child->style()->logicalHeight().isSpecified()) {
             LogicalExtentComputedValues computedValues;
@@ -245,7 +245,7 @@
     repainter.repaintAfterLayout();
 
     m_isNestedLayout = false;
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderLazyBlock.h b/Source/core/rendering/RenderLazyBlock.h
index 442aeb6..5f13f90 100644
--- a/Source/core/rendering/RenderLazyBlock.h
+++ b/Source/core/rendering/RenderLazyBlock.h
@@ -45,7 +45,7 @@
 
     void markForNestedLayout()
     {
-        setNeedsLayout(true);
+        setNeedsLayout();
         m_isNestedLayout = true;
     }
 
diff --git a/Source/core/rendering/RenderListBox.cpp b/Source/core/rendering/RenderListBox.cpp
index a2b87f8..4759684 100644
--- a/Source/core/rendering/RenderListBox.cpp
+++ b/Source/core/rendering/RenderListBox.cpp
@@ -727,7 +727,7 @@
 bool RenderListBox::isActive() const
 {
     Page* page = frame()->page();
-    return page && page->focusController()->isActive();
+    return page && page->focusController().isActive();
 }
 
 void RenderListBox::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
diff --git a/Source/core/rendering/RenderListItem.cpp b/Source/core/rendering/RenderListItem.cpp
index 0944508..918224a 100644
--- a/Source/core/rendering/RenderListItem.cpp
+++ b/Source/core/rendering/RenderListItem.cpp
@@ -392,16 +392,16 @@
             bool propagateLayoutOverflow = true;
             do {
                 o = o->parentBox();
-                if (o->hasOverflowClip())
-                    propagateVisualOverflow = false;
                 if (o->isRenderBlock()) {
                     if (propagateVisualOverflow)
-                        toRenderBlock(o)->addVisualOverflow(markerRect);
+                        toRenderBlock(o)->addContentsVisualOverflow(markerRect);
                     if (propagateLayoutOverflow)
                         toRenderBlock(o)->addLayoutOverflow(markerRect);
                 }
-                if (o->hasOverflowClip())
+                if (o->hasOverflowClip()) {
                     propagateLayoutOverflow = false;
+                    propagateVisualOverflow = false;
+                }
                 if (o->hasSelfPaintingLayer())
                     propagateVisualOverflow = false;
                 markerRect.moveBy(-o->location());
diff --git a/Source/core/rendering/RenderListMarker.cpp b/Source/core/rendering/RenderListMarker.cpp
index bc4aaad..d63728e 100644
--- a/Source/core/rendering/RenderListMarker.cpp
+++ b/Source/core/rendering/RenderListMarker.cpp
@@ -26,7 +26,7 @@
 #include "core/rendering/RenderListMarker.h"
 
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/RenderLayer.h"
@@ -1343,7 +1343,7 @@
     if (endMargin.isFixed())
         setMarginEnd(endMargin.value());
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderListMarker::imageChanged(WrappedImagePtr o, const IntRect*)
diff --git a/Source/core/rendering/RenderMarquee.cpp b/Source/core/rendering/RenderMarquee.cpp
index eed4b72..ecfff0d 100644
--- a/Source/core/rendering/RenderMarquee.cpp
+++ b/Source/core/rendering/RenderMarquee.cpp
@@ -269,7 +269,7 @@
     // Check the loop count to see if we should now stop.
     bool activate = (m_totalLoops <= 0 || m_currentLoop < m_totalLoops);
     if (activate && !m_timer.isActive())
-        setNeedsLayout(true);
+        setNeedsLayout();
     else if (!activate && m_timer.isActive())
         m_timer.stop();
 }
diff --git a/Source/core/rendering/RenderMedia.cpp b/Source/core/rendering/RenderMedia.cpp
index 48246c9..662cbeb 100644
--- a/Source/core/rendering/RenderMedia.cpp
+++ b/Source/core/rendering/RenderMedia.cpp
@@ -88,7 +88,7 @@
     controlsRenderer->style()->setHeight(Length(newSize.height(), Fixed));
     controlsRenderer->style()->setWidth(Length(newSize.width(), Fixed));
     controlsRenderer->forceLayout();
-    setChildNeedsLayout(false);
+    clearNeedsLayout();
 
     statePusher.pop();
 }
diff --git a/Source/core/rendering/RenderMultiColumnBlock.cpp b/Source/core/rendering/RenderMultiColumnBlock.cpp
index 8831a88..5ab8cb6 100644
--- a/Source/core/rendering/RenderMultiColumnBlock.cpp
+++ b/Source/core/rendering/RenderMultiColumnBlock.cpp
@@ -115,7 +115,7 @@
             if (childBox != m_flowThread && childBox->isRenderMultiColumnSet()) {
                 RenderMultiColumnSet* multicolSet = toRenderMultiColumnSet(childBox);
                 if (multicolSet->calculateBalancedHeight(firstPass)) {
-                    multicolSet->setChildNeedsLayout(true, MarkOnlyThis);
+                    multicolSet->setChildNeedsLayout(MarkOnlyThis);
                     needsRelayout = true;
                 }
             }
@@ -124,8 +124,8 @@
         if (needsRelayout) {
             // Layout again. Column balancing resulted in a new height.
             neededRelayout = true;
-            m_flowThread->setChildNeedsLayout(true, MarkOnlyThis);
-            setChildNeedsLayout(true, MarkOnlyThis);
+            m_flowThread->setChildNeedsLayout(MarkOnlyThis);
+            setChildNeedsLayout(MarkOnlyThis);
             if (firstPass)
                 statePusher.pop();
             layoutBlock(false);
@@ -170,7 +170,7 @@
         m_flowThread->invalidateRegions();
 
     if (relayoutChildren)
-        m_flowThread->setChildNeedsLayout(true, MarkOnlyThis);
+        m_flowThread->setChildNeedsLayout(MarkOnlyThis);
 
     setLogicalTopForChild(m_flowThread, borderBefore() + paddingBefore());
     m_flowThread->layoutIfNeeded();
diff --git a/Source/core/rendering/RenderNamedFlowThread.cpp b/Source/core/rendering/RenderNamedFlowThread.cpp
index 97774fb..bc72e9a 100644
--- a/Source/core/rendering/RenderNamedFlowThread.cpp
+++ b/Source/core/rendering/RenderNamedFlowThread.cpp
@@ -29,7 +29,7 @@
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/NamedFlow.h"
-#include "core/dom/NodeRenderingContext.h"
+#include "core/dom/NodeRenderingTraversal.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Position.h"
 #include "core/dom/Range.h"
@@ -90,6 +90,18 @@
     m_contentNodes.clear();
 }
 
+void RenderNamedFlowThread::updateWritingMode()
+{
+    if (RenderRegion* firstRegion = m_regionList.first()) {
+        if (style()->writingMode() != firstRegion->style()->writingMode()) {
+            // The first region defines the principal writing mode for the entire flow.
+            RefPtr<RenderStyle> newStyle = RenderStyle::clone(style());
+            newStyle->setWritingMode(firstRegion->style()->writingMode());
+            setStyle(newStyle);
+        }
+    }
+}
+
 RenderObject* RenderNamedFlowThread::nextRendererForNode(Node* node) const
 {
     FlowThreadChildList::const_iterator it = m_flowThreadChildList.begin();
@@ -244,6 +256,9 @@
 
     renderRegion->setIsValid(true);
     addRegionToList(m_regionList, renderRegion);
+
+    if (m_regionList.first() == renderRegion)
+        updateWritingMode();
 }
 
 void RenderNamedFlowThread::addRegionToThread(RenderRegion* renderRegion)
@@ -283,6 +298,7 @@
     }
 
     ASSERT(m_regionList.contains(renderRegion));
+    bool wasFirst = m_regionList.first() == renderRegion;
     m_regionList.remove(renderRegion);
 
     if (canBeDestroyed())
@@ -291,10 +307,18 @@
     // After removing all the regions in the flow the following layout needs to dispatch the regionLayoutUpdate event
     if (m_regionList.isEmpty())
         setDispatchRegionLayoutUpdateEvent(true);
+    else if (wasFirst)
+        updateWritingMode();
 
     invalidateRegions();
 }
 
+void RenderNamedFlowThread::regionChangedWritingMode(RenderRegion* region)
+{
+    if (m_regionList.first() == region)
+        updateWritingMode();
+}
+
 void RenderNamedFlowThread::computeOversetStateForRegions(LayoutUnit oldClientAfterEdge)
 {
     LayoutUnit height = oldClientAfterEdge;
@@ -455,18 +479,15 @@
 
 bool RenderNamedFlowThread::isChildAllowed(RenderObject* child, RenderStyle* style) const
 {
-    ASSERT(child);
-    ASSERT(style);
-
     if (!child->node())
         return true;
 
     ASSERT(child->node()->isElementNode());
-    RenderObject* parentRenderer = NodeRenderingContext(child->node()).parentRenderer();
-    if (!parentRenderer)
+    Node* originalParent = NodeRenderingTraversal::parent(child->node());
+    if (!originalParent || !originalParent->renderer())
         return true;
 
-    return parentRenderer->isChildAllowed(child, style);
+    return originalParent->renderer()->isChildAllowed(child, style);
 }
 
 void RenderNamedFlowThread::dispatchRegionLayoutUpdateEvent()
diff --git a/Source/core/rendering/RenderNamedFlowThread.h b/Source/core/rendering/RenderNamedFlowThread.h
index 1e41f99..c0dec6c 100644
--- a/Source/core/rendering/RenderNamedFlowThread.h
+++ b/Source/core/rendering/RenderNamedFlowThread.h
@@ -68,6 +68,8 @@
     virtual void addRegionToThread(RenderRegion*) OVERRIDE;
     virtual void removeRegionFromThread(RenderRegion*) OVERRIDE;
 
+    virtual void regionChangedWritingMode(RenderRegion*) OVERRIDE;
+
     bool overset() const { return m_overset; }
     void computeOversetStateForRegions(LayoutUnit oldClientAfterEdge);
 
@@ -104,6 +106,7 @@
     void regionLayoutUpdateEventTimerFired(Timer<RenderNamedFlowThread>*);
     void regionOversetChangeEventTimerFired(Timer<RenderNamedFlowThread>*);
     void clearContentNodes();
+    void updateWritingMode();
 
 private:
     // Observer flow threads have invalid regions that depend on the state of this thread
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index eb5cacb..58bbf32 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -223,7 +223,7 @@
 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, renderObjectCounter, ("RenderObject"));
 
 RenderObject::RenderObject(Node* node)
-    : CachedImageClient()
+    : ImageResourceClient()
     , m_style(0)
     , m_node(node)
     , m_parent(0)
@@ -2782,7 +2782,7 @@
         ASSERT(!child->needsLayout());
         child = child->nextSibling();
     }
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 // FIXME: Do we need this method at all? If setNeedsLayout early returns in all the right places,
@@ -2791,7 +2791,7 @@
 {
     // This is the only way it's safe to use MarkOnlyThis (i.e. if we're immediately going to call layout).
     // FIXME: Add asserts that we only ever do the MarkOnlyThis behavior from here.
-    setNeedsLayout(true, MarkOnlyThis);
+    setNeedsLayout(MarkOnlyThis);
     layout();
 }
 
@@ -2799,7 +2799,7 @@
 // I don't think it does and we should change all callers to use forceLayout.
 void RenderObject::forceChildLayout()
 {
-    setChildNeedsLayout(true, MarkOnlyThis);
+    setChildNeedsLayout(MarkOnlyThis);
     forceLayout();
 }
 
@@ -2994,7 +2994,7 @@
         curr->collectAnnotatedRegions(regions);
 }
 
-bool RenderObject::willRenderImage(CachedImage*)
+bool RenderObject::willRenderImage(ImageResource*)
 {
     // Without visibility we won't render (and therefore don't care about animation).
     if (style()->visibility() != VISIBLE)
@@ -3072,7 +3072,7 @@
     return parentNode && toElement(parentNode)->isInert();
 }
 
-void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
+void RenderObject::imageChanged(ImageResource* image, const IntRect* rect)
 {
     imageChanged(static_cast<WrappedImagePtr>(image), rect);
 }
diff --git a/Source/core/rendering/RenderObject.h b/Source/core/rendering/RenderObject.h
index c8dd232..4d34112 100644
--- a/Source/core/rendering/RenderObject.h
+++ b/Source/core/rendering/RenderObject.h
@@ -29,7 +29,7 @@
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/Element.h"
 #include "core/dom/Position.h"
-#include "core/loader/cache/CachedImageClient.h"
+#include "core/loader/cache/ImageResourceClient.h"
 #include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/graphics/transforms/TransformationMatrix.h"
@@ -135,7 +135,7 @@
 #endif
 
 // Base class for all rendering tree objects.
-class RenderObject : public CachedImageClient {
+class RenderObject : public ImageResourceClient {
     friend class RenderBlock;
     friend class RenderLayer;
     friend class RenderObjectChildList;
@@ -406,7 +406,7 @@
             if (!s_ancestorLineboxDirtySet)
                 s_ancestorLineboxDirtySet = new RenderObjectAncestorLineboxDirtySet;
             s_ancestorLineboxDirtySet->add(this);
-            setNeedsLayout(true);
+            setNeedsLayout();
         } else if (s_ancestorLineboxDirtySet) {
             s_ancestorLineboxDirtySet->remove(this);
             if (s_ancestorLineboxDirtySet->isEmpty()) {
@@ -622,8 +622,9 @@
     Element* offsetParent() const;
 
     void markContainingBlocksForLayout(bool scheduleRelayout = true, RenderObject* newRoot = 0);
-    void setNeedsLayout(bool needsLayout, MarkingBehavior = MarkContainingBlockChain);
-    void setChildNeedsLayout(bool childNeedsLayout, MarkingBehavior = MarkContainingBlockChain);
+    void setNeedsLayout(MarkingBehavior = MarkContainingBlockChain);
+    void clearNeedsLayout();
+    void setChildNeedsLayout(MarkingBehavior = MarkContainingBlockChain);
     void setNeedsPositionedMovementLayout();
     void setNeedsSimplifiedNormalFlowLayout();
     void setPreferredLogicalWidthsDirty(bool, MarkingBehavior = MarkContainingBlockChain);
@@ -631,7 +632,7 @@
 
     void setNeedsLayoutAndPrefWidthsRecalc()
     {
-        setNeedsLayout(true);
+        setNeedsLayout();
         setPreferredLogicalWidthsDirty(true);
     }
 
@@ -945,9 +946,9 @@
     virtual int previousOffsetForBackwardDeletion(int current) const;
     virtual int nextOffset(int current) const;
 
-    virtual void imageChanged(CachedImage*, const IntRect* = 0);
+    virtual void imageChanged(ImageResource*, const IntRect* = 0);
     virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) { }
-    virtual bool willRenderImage(CachedImage*);
+    virtual bool willRenderImage(ImageResource*);
 
     void selectionStartEnd(int& spos, int& epos) const;
 
@@ -1196,6 +1197,7 @@
 
     RenderObjectBitfields m_bitfields;
 
+    // FIXME: These private methods are silly. We should just call m_bitfields.setXXX(b) directly.
     void setNeedsPositionedMovementLayout(bool b) { m_bitfields.setNeedsPositionedMovementLayout(b); }
     void setNormalChildNeedsLayout(bool b) { m_bitfields.setNormalChildNeedsLayout(b); }
     void setPosChildNeedsLayout(bool b) { m_bitfields.setPosChildNeedsLayout(b); }
@@ -1238,45 +1240,40 @@
     return isBeforeContent() || isAfterContent();
 }
 
-inline void RenderObject::setNeedsLayout(bool needsLayout, MarkingBehavior markParents)
+inline void RenderObject::setNeedsLayout(MarkingBehavior markParents)
 {
+    ASSERT(!isSetNeedsLayoutForbidden());
     bool alreadyNeededLayout = m_bitfields.needsLayout();
-    m_bitfields.setNeedsLayout(needsLayout);
-    if (needsLayout) {
-        ASSERT(!isSetNeedsLayoutForbidden());
-        if (!alreadyNeededLayout) {
-            if (markParents == MarkContainingBlockChain)
-                markContainingBlocksForLayout();
-            if (hasLayer())
-                setLayerNeedsFullRepaint();
-        }
-    } else {
-        setEverHadLayout(true);
-        setPosChildNeedsLayout(false);
-        setNeedsSimplifiedNormalFlowLayout(false);
-        setNormalChildNeedsLayout(false);
-        setNeedsPositionedMovementLayout(false);
-        setAncestorLineBoxDirty(false);
-#ifndef NDEBUG
-        checkBlockPositionedObjectsNeedLayout();
-#endif
+    m_bitfields.setNeedsLayout(true);
+    if (!alreadyNeededLayout) {
+        if (markParents == MarkContainingBlockChain)
+            markContainingBlocksForLayout();
+        if (hasLayer())
+            setLayerNeedsFullRepaint();
     }
 }
 
-inline void RenderObject::setChildNeedsLayout(bool childNeedsLayout, MarkingBehavior markParents)
+inline void RenderObject::clearNeedsLayout()
 {
+    m_bitfields.setNeedsLayout(false);
+    setEverHadLayout(true);
+    setPosChildNeedsLayout(false);
+    setNeedsSimplifiedNormalFlowLayout(false);
+    setNormalChildNeedsLayout(false);
+    setNeedsPositionedMovementLayout(false);
+    setAncestorLineBoxDirty(false);
+#ifndef NDEBUG
+    checkBlockPositionedObjectsNeedLayout();
+#endif
+}
+
+inline void RenderObject::setChildNeedsLayout(MarkingBehavior markParents)
+{
+    ASSERT(!isSetNeedsLayoutForbidden());
     bool alreadyNeededLayout = normalChildNeedsLayout();
-    setNormalChildNeedsLayout(childNeedsLayout);
-    if (childNeedsLayout) {
-        ASSERT(!isSetNeedsLayoutForbidden());
-        if (!alreadyNeededLayout && markParents == MarkContainingBlockChain)
-            markContainingBlocksForLayout();
-    } else {
-        setPosChildNeedsLayout(false);
-        setNeedsSimplifiedNormalFlowLayout(false);
-        setNormalChildNeedsLayout(false);
-        setNeedsPositionedMovementLayout(false);
-    }
+    setNormalChildNeedsLayout(true);
+    if (!alreadyNeededLayout && markParents == MarkContainingBlockChain)
+        markContainingBlocksForLayout();
 }
 
 inline void RenderObject::setNeedsPositionedMovementLayout()
diff --git a/Source/core/rendering/RenderObjectChildList.cpp b/Source/core/rendering/RenderObjectChildList.cpp
index e14404e..2f3b471 100644
--- a/Source/core/rendering/RenderObjectChildList.cpp
+++ b/Source/core/rendering/RenderObjectChildList.cpp
@@ -159,7 +159,7 @@
 
     newChild->setNeedsLayoutAndPrefWidthsRecalc();
     if (!owner->normalChildNeedsLayout())
-        owner->setChildNeedsLayout(true); // We may supply the static position for an absolute positioned child.
+        owner->setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
 
     if (AXObjectCache* cache = owner->document()->axObjectCache())
         cache->childrenChanged(owner);
diff --git a/Source/core/rendering/RenderOverflow.h b/Source/core/rendering/RenderOverflow.h
index d01d3ba..1c5417f 100644
--- a/Source/core/rendering/RenderOverflow.h
+++ b/Source/core/rendering/RenderOverflow.h
@@ -48,6 +48,7 @@
 
     const LayoutRect layoutOverflowRect() const { return m_layoutOverflow; }
     const LayoutRect visualOverflowRect() const { return m_visualOverflow; }
+    LayoutRect contentsVisualOverflowRect() const { return m_contentsVisualOverflow; }
 
     void setMinYLayoutOverflow(LayoutUnit overflow) { m_layoutOverflow.setY(overflow); }
     void setMaxYLayoutOverflow(LayoutUnit overflow) { m_layoutOverflow.setHeight(overflow - m_layoutOverflow.y()); }
@@ -63,6 +64,7 @@
 
     void addLayoutOverflow(const LayoutRect&);
     void addVisualOverflow(const LayoutRect&);
+    void addContentsVisualOverflow(const LayoutRect& rect) { m_contentsVisualOverflow.unite(rect); }
 
     void setLayoutOverflow(const LayoutRect&);
     void setVisualOverflow(const LayoutRect&);
@@ -73,6 +75,7 @@
 private:
     LayoutRect m_layoutOverflow;
     LayoutRect m_visualOverflow;
+    LayoutRect m_contentsVisualOverflow;
 
     LayoutUnit m_layoutClientAfterEdge;
 };
@@ -81,6 +84,7 @@
 {
     m_layoutOverflow.move(dx, dy);
     m_visualOverflow.move(dx, dy);
+    m_contentsVisualOverflow.move(dx, dy);
 }
 
 inline void RenderOverflow::addLayoutOverflow(const LayoutRect& rect)
diff --git a/Source/core/rendering/RenderOverflowTest.cpp b/Source/core/rendering/RenderOverflowTest.cpp
new file mode 100644
index 0000000..0a5b7c3
--- /dev/null
+++ b/Source/core/rendering/RenderOverflowTest.cpp
@@ -0,0 +1,194 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderOverflow.h"
+
+#include "core/platform/graphics/LayoutRect.h"
+
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace WebCore {
+
+// FIXME: Move this somewhere more generic.
+void PrintTo(const LayoutRect& rect, std::ostream* os)
+{
+    *os << "LayoutRect("
+        << rect.x().toFloat() << ", "
+        << rect.y().toFloat() << ", "
+        << rect.width().toFloat() << ", "
+        << rect.height().toFloat() << ")";
+}
+
+} // namespace WebCore
+
+namespace {
+
+LayoutRect initialLayoutOverflow()
+{
+    return LayoutRect(10, 10, 80, 80);
+}
+
+LayoutRect initialVisualOverflow()
+{
+    return LayoutRect(0, 0, 100, 100);
+}
+
+class RenderOverflowTest : public testing::Test {
+protected:
+    RenderOverflowTest() : m_overflow(initialLayoutOverflow(), initialVisualOverflow()) { }
+    RenderOverflow m_overflow;
+};
+
+TEST_F(RenderOverflowTest, InitialOverflowRects)
+{
+    EXPECT_EQ(initialLayoutOverflow(), m_overflow.layoutOverflowRect());
+    EXPECT_EQ(initialVisualOverflow(), m_overflow.visualOverflowRect());
+    EXPECT_TRUE(m_overflow.contentsVisualOverflowRect().isEmpty());
+}
+
+TEST_F(RenderOverflowTest, AddLayoutOverflowOutsideExpandsRect)
+{
+    m_overflow.addLayoutOverflow(LayoutRect(0, 10, 30, 10));
+    EXPECT_EQ(LayoutRect(0, 10, 90, 80), m_overflow.layoutOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddLayoutOverflowInsideDoesNotAffectRect)
+{
+    m_overflow.addLayoutOverflow(LayoutRect(50, 50, 10, 20));
+    EXPECT_EQ(initialLayoutOverflow(), m_overflow.layoutOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddLayoutOverflowEmpty)
+{
+    // This test documents the existing behavior so that we are aware when/if
+    // it changes. It would also be reasonable for addLayoutOverflow to be
+    // a no-op in this situation.
+    m_overflow.addLayoutOverflow(LayoutRect(200, 200, 0, 0));
+    EXPECT_EQ(LayoutRect(10, 10, 190, 190), m_overflow.layoutOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddLayoutOverflowDoesNotAffectVisualOverflow)
+{
+    m_overflow.addLayoutOverflow(LayoutRect(300, 300, 300, 300));
+    EXPECT_EQ(initialVisualOverflow(), m_overflow.visualOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddLayoutOverflowDoesNotAffectContentsVisualOverflow)
+{
+    m_overflow.addLayoutOverflow(LayoutRect(300, 300, 300, 300));
+    EXPECT_TRUE(m_overflow.contentsVisualOverflowRect().isEmpty());
+}
+
+TEST_F(RenderOverflowTest, AddVisualOverflowOutsideExpandsRect)
+{
+    m_overflow.addVisualOverflow(LayoutRect(150, -50, 10, 10));
+    EXPECT_EQ(LayoutRect(0, -50, 160, 150), m_overflow.visualOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddVisualOverflowInsideDoesNotAffectRect)
+{
+    m_overflow.addVisualOverflow(LayoutRect(0, 10, 90, 90));
+    EXPECT_EQ(initialVisualOverflow(), m_overflow.visualOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddVisualOverflowEmpty)
+{
+    // This test documents the existing behavior so that we are aware when/if
+    // it changes. It would also be reasonable for addVisualOverflow to be
+    // a no-op in this situation.
+    m_overflow.addVisualOverflow(LayoutRect(200, 200, 0, 0));
+    EXPECT_EQ(LayoutRect(0, 0, 200, 200), m_overflow.visualOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddVisualOverflowDoesNotAffectLayoutOverflow)
+{
+    m_overflow.addVisualOverflow(LayoutRect(300, 300, 300, 300));
+    EXPECT_EQ(initialLayoutOverflow(), m_overflow.layoutOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddVisualOverflowDoesNotAffectContentsVisualOverflow)
+{
+    m_overflow.addVisualOverflow(LayoutRect(300, 300, 300, 300));
+    EXPECT_TRUE(m_overflow.contentsVisualOverflowRect().isEmpty());
+}
+
+TEST_F(RenderOverflowTest, AddContentsVisualOverflowFirstCall)
+{
+    m_overflow.addContentsVisualOverflow(LayoutRect(0, 0, 10, 10));
+    EXPECT_EQ(LayoutRect(0, 0, 10, 10), m_overflow.contentsVisualOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddContentsVisualOverflowUnitesRects)
+{
+    m_overflow.addContentsVisualOverflow(LayoutRect(0, 0, 10, 10));
+    m_overflow.addContentsVisualOverflow(LayoutRect(80, 80, 10, 10));
+    EXPECT_EQ(LayoutRect(0, 0, 90, 90), m_overflow.contentsVisualOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddContentsVisualOverflowRectWithinRect)
+{
+    m_overflow.addContentsVisualOverflow(LayoutRect(0, 0, 10, 10));
+    m_overflow.addContentsVisualOverflow(LayoutRect(2, 2, 5, 5));
+    EXPECT_EQ(LayoutRect(0, 0, 10, 10), m_overflow.contentsVisualOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, AddContentsVisualOverflowEmpty)
+{
+    // This test documents the existing behavior so that we are aware when/if
+    // it changes. It would also be reasonable for addContentsVisualOverflow to
+    // expand in this situation.
+    m_overflow.addContentsVisualOverflow(LayoutRect(0, 0, 10, 10));
+    m_overflow.addContentsVisualOverflow(LayoutRect(20, 20, 0, 0));
+    EXPECT_EQ(LayoutRect(0, 0, 10, 10), m_overflow.contentsVisualOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, MoveAffectsLayoutOverflow)
+{
+    m_overflow.move(500, 100);
+    EXPECT_EQ(LayoutRect(510, 110, 80, 80), m_overflow.layoutOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, MoveAffectsVisualOverflow)
+{
+    m_overflow.move(500, 100);
+    EXPECT_EQ(LayoutRect(500, 100, 100, 100), m_overflow.visualOverflowRect());
+}
+
+TEST_F(RenderOverflowTest, MoveAffectsContentsVisualOverflow)
+{
+    m_overflow.addContentsVisualOverflow(LayoutRect(0, 0, 10, 10));
+    m_overflow.move(500, 100);
+    EXPECT_EQ(LayoutRect(500, 100, 10, 10), m_overflow.contentsVisualOverflowRect());
+}
+
+} // namespace
diff --git a/Source/core/rendering/RenderRegion.cpp b/Source/core/rendering/RenderRegion.cpp
index 203d207..1a739f8 100644
--- a/Source/core/rendering/RenderRegion.cpp
+++ b/Source/core/rendering/RenderRegion.cpp
@@ -270,6 +270,9 @@
 
     checkRegionStyle();
     updateRegionHasAutoLogicalHeightFlag();
+
+    if (oldStyle && oldStyle->writingMode() != style()->writingMode())
+        m_flowThread->regionChangedWritingMode(this);
 }
 
 void RenderRegion::layoutBlock(bool relayoutChildren, LayoutUnit)
diff --git a/Source/core/rendering/RenderReplaced.cpp b/Source/core/rendering/RenderReplaced.cpp
index ff3d191..8b229f4 100644
--- a/Source/core/rendering/RenderReplaced.cpp
+++ b/Source/core/rendering/RenderReplaced.cpp
@@ -91,7 +91,7 @@
     invalidateBackgroundObscurationStatus();
 
     repainter.repaintAfterLayout();
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderReplaced::intrinsicSizeChanged()
diff --git a/Source/core/rendering/RenderReplica.cpp b/Source/core/rendering/RenderReplica.cpp
index 3c6e78d..3328ad9 100644
--- a/Source/core/rendering/RenderReplica.cpp
+++ b/Source/core/rendering/RenderReplica.cpp
@@ -59,7 +59,7 @@
     StackStats::LayoutCheckPoint layoutCheckPoint;
     setFrameRect(parentBox()->borderBoxRect());
     updateLayerTransform();
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderReplica::computePreferredLogicalWidths()
diff --git a/Source/core/rendering/RenderRubyRun.cpp b/Source/core/rendering/RenderRubyRun.cpp
index 80b4cbd..a0d3c10 100644
--- a/Source/core/rendering/RenderRubyRun.cpp
+++ b/Source/core/rendering/RenderRubyRun.cpp
@@ -222,7 +222,7 @@
     if (!rt)
         return 0;
     if (relayoutChildren)
-        rt->setChildNeedsLayout(true, MarkOnlyThis);
+        rt->setChildNeedsLayout(MarkOnlyThis);
     rt->layoutIfNeeded();
     return rt;
 }
diff --git a/Source/core/rendering/RenderScrollbar.cpp b/Source/core/rendering/RenderScrollbar.cpp
index 1f39c36..9612040 100644
--- a/Source/core/rendering/RenderScrollbar.cpp
+++ b/Source/core/rendering/RenderScrollbar.cpp
@@ -189,7 +189,7 @@
     if (newThickness != oldThickness) {
         setFrameRect(IntRect(location(), IntSize(isHorizontal ? width() : newThickness, isHorizontal ? newThickness : height())));
         if (RenderBox* box = owningRenderer())
-            box->setChildNeedsLayout(true);
+            box->setChildNeedsLayout();
     }
 }
 
diff --git a/Source/core/rendering/RenderScrollbarPart.cpp b/Source/core/rendering/RenderScrollbarPart.cpp
index 5d1dac3..45878a8 100644
--- a/Source/core/rendering/RenderScrollbarPart.cpp
+++ b/Source/core/rendering/RenderScrollbarPart.cpp
@@ -62,7 +62,7 @@
     else
         layoutVerticalPart();
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderScrollbarPart::layoutHorizontalPart()
diff --git a/Source/core/rendering/RenderScrollbarTheme.h b/Source/core/rendering/RenderScrollbarTheme.h
index d718f5f..8da44cd 100644
--- a/Source/core/rendering/RenderScrollbarTheme.h
+++ b/Source/core/rendering/RenderScrollbarTheme.h
@@ -26,7 +26,7 @@
 #ifndef RenderScrollbarTheme_h
 #define RenderScrollbarTheme_h
 
-#include "core/platform/ScrollbarThemeComposite.h"
+#include "core/platform/ScrollbarTheme.h"
 
 namespace WebCore {
 
@@ -34,48 +34,48 @@
 class Scrollbar;
 class ScrollView;
 
-class RenderScrollbarTheme : public ScrollbarThemeComposite {
+class RenderScrollbarTheme : public ScrollbarTheme {
 public:
-    virtual ~RenderScrollbarTheme() {};
+    virtual ~RenderScrollbarTheme() { }
 
-    virtual int scrollbarThickness(ScrollbarControlSize controlSize) { return ScrollbarTheme::theme()->scrollbarThickness(controlSize); }
+    virtual int scrollbarThickness(ScrollbarControlSize controlSize) OVERRIDE { return ScrollbarTheme::theme()->scrollbarThickness(controlSize); }
 
-    virtual ScrollbarButtonsPlacement buttonsPlacement() const { return ScrollbarTheme::theme()->buttonsPlacement(); }
+    virtual ScrollbarButtonsPlacement buttonsPlacement() const OVERRIDE { return ScrollbarTheme::theme()->buttonsPlacement(); }
 
-    virtual bool supportsControlTints() const { return true; }
+    virtual bool supportsControlTints() const OVERRIDE { return true; }
 
-    virtual void paintScrollCorner(ScrollView*, GraphicsContext* context, const IntRect& cornerRect);
+    virtual void paintScrollCorner(ScrollView*, GraphicsContext*, const IntRect& cornerRect) OVERRIDE;
 
-    virtual bool shouldCenterOnThumb(ScrollbarThemeClient* scrollbar, const PlatformMouseEvent& event) { return ScrollbarTheme::theme()->shouldCenterOnThumb(scrollbar, event); }
+    virtual bool shouldCenterOnThumb(ScrollbarThemeClient* scrollbar, const PlatformMouseEvent& event) OVERRIDE { return ScrollbarTheme::theme()->shouldCenterOnThumb(scrollbar, event); }
 
-    virtual double initialAutoscrollTimerDelay() { return ScrollbarTheme::theme()->initialAutoscrollTimerDelay(); }
-    virtual double autoscrollTimerDelay() { return ScrollbarTheme::theme()->autoscrollTimerDelay(); }
+    virtual double initialAutoscrollTimerDelay() OVERRIDE { return ScrollbarTheme::theme()->initialAutoscrollTimerDelay(); }
+    virtual double autoscrollTimerDelay() OVERRIDE { return ScrollbarTheme::theme()->autoscrollTimerDelay(); }
 
-    virtual void registerScrollbar(ScrollbarThemeClient* scrollbar) { return ScrollbarTheme::theme()->registerScrollbar(scrollbar); }
-    virtual void unregisterScrollbar(ScrollbarThemeClient* scrollbar) { return ScrollbarTheme::theme()->unregisterScrollbar(scrollbar); }
+    virtual void registerScrollbar(ScrollbarThemeClient* scrollbar) OVERRIDE { return ScrollbarTheme::theme()->registerScrollbar(scrollbar); }
+    virtual void unregisterScrollbar(ScrollbarThemeClient* scrollbar) OVERRIDE { return ScrollbarTheme::theme()->unregisterScrollbar(scrollbar); }
 
-    virtual int minimumThumbLength(ScrollbarThemeClient*);
+    virtual int minimumThumbLength(ScrollbarThemeClient*) OVERRIDE;
 
     void buttonSizesAlongTrackAxis(ScrollbarThemeClient*, int& beforeSize, int& afterSize);
 
     static RenderScrollbarTheme* renderScrollbarTheme();
 
 protected:
-    virtual bool hasButtons(ScrollbarThemeClient*);
-    virtual bool hasThumb(ScrollbarThemeClient*);
+    virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE;
+    virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
 
-    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
-    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
-    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false);
+    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
+    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
+    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
 
-    virtual void paintScrollbarBackground(GraphicsContext*, ScrollbarThemeClient*);
-    virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
-    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
-    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
+    virtual void paintScrollbarBackground(GraphicsContext*, ScrollbarThemeClient*) OVERRIDE;
+    virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
+    virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) OVERRIDE;
+    virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) OVERRIDE;
+    virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
     virtual void paintTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
 
-    virtual IntRect constrainTrackRectToTrackPieces(ScrollbarThemeClient*, const IntRect&);
+    virtual IntRect constrainTrackRectToTrackPieces(ScrollbarThemeClient*, const IntRect&) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderSearchField.cpp b/Source/core/rendering/RenderSearchField.cpp
index 11ee314..4e4244c 100644
--- a/Source/core/rendering/RenderSearchField.cpp
+++ b/Source/core/rendering/RenderSearchField.cpp
@@ -25,6 +25,7 @@
 #include "core/rendering/RenderSearchField.h"
 
 #include "core/html/HTMLInputElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
 
 using namespace std;
 
@@ -44,25 +45,25 @@
 {
 }
 
-inline HTMLElement* RenderSearchField::searchDecorationElement() const
+inline Element* RenderSearchField::searchDecorationElement() const
 {
-    return inputElement()->searchDecorationElement();
+    return inputElement()->uaShadowElementById(ShadowElementNames::searchDecoration());
 }
 
-inline HTMLElement* RenderSearchField::cancelButtonElement() const
+inline Element* RenderSearchField::cancelButtonElement() const
 {
-    return inputElement()->cancelButtonElement();
+    return inputElement()->uaShadowElementById(ShadowElementNames::clearButton());
 }
 
 LayoutUnit RenderSearchField::computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const
 {
-    HTMLElement* searchDecoration = searchDecorationElement();
+    Element* searchDecoration = searchDecorationElement();
     if (RenderBox* decorationRenderer = searchDecoration ? searchDecoration->renderBox() : 0) {
         decorationRenderer->updateLogicalHeight();
         nonContentHeight = max(nonContentHeight, decorationRenderer->borderAndPaddingLogicalHeight() + decorationRenderer->marginLogicalHeight());
         lineHeight = max(lineHeight, decorationRenderer->logicalHeight());
     }
-    HTMLElement* cancelButton = cancelButtonElement();
+    Element* cancelButton = cancelButtonElement();
     if (RenderBox* cancelRenderer = cancelButton ? cancelButton->renderBox() : 0) {
         cancelRenderer->updateLogicalHeight();
         nonContentHeight = max(nonContentHeight, cancelRenderer->borderAndPaddingLogicalHeight() + cancelRenderer->marginLogicalHeight());
diff --git a/Source/core/rendering/RenderSearchField.h b/Source/core/rendering/RenderSearchField.h
index c793ab1..d8617ae 100644
--- a/Source/core/rendering/RenderSearchField.h
+++ b/Source/core/rendering/RenderSearchField.h
@@ -45,8 +45,8 @@
     virtual void updateFromElement() OVERRIDE;
     EVisibility visibilityForCancelButton() const;
 
-    HTMLElement* searchDecorationElement() const;
-    HTMLElement* cancelButtonElement() const;
+    Element* searchDecorationElement() const;
+    Element* cancelButtonElement() const;
 };
 
 inline RenderSearchField* toRenderSearchField(RenderObject* object)
diff --git a/Source/core/rendering/RenderTable.cpp b/Source/core/rendering/RenderTable.cpp
index f086f2a..12ea553 100644
--- a/Source/core/rendering/RenderTable.cpp
+++ b/Source/core/rendering/RenderTable.cpp
@@ -424,7 +424,7 @@
 
     if (logicalWidth() != oldLogicalWidth) {
         for (unsigned i = 0; i < m_captions.size(); i++)
-            m_captions[i]->setNeedsLayout(true, MarkOnlyThis);
+            m_captions[i]->setNeedsLayout(MarkOnlyThis);
     }
     // FIXME: The optimisation below doesn't work since the internal table
     // layout could have changed.  we need to add a flag to the table
@@ -444,7 +444,7 @@
         if (child->isTableSection()) {
             RenderTableSection* section = toRenderTableSection(child);
             if (m_columnLogicalWidthChanged)
-                section->setChildNeedsLayout(true, MarkOnlyThis);
+                section->setChildNeedsLayout(MarkOnlyThis);
             section->layoutIfNeeded();
             totalSectionLogicalHeight += section->calcRowLogicalHeight();
             if (collapsing)
@@ -566,7 +566,7 @@
     }
 
     m_columnLogicalWidthChanged = false;
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 // Collect all the unique border values that we want to paint in a sorted list.
@@ -637,7 +637,7 @@
             return;
     }
 
-    bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
+    bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset, ForceContentsClip);
     paintObject(paintInfo, adjustedPaintOffset);
     if (pushedClip)
         popContentsClip(paintInfo, paintPhase, adjustedPaintOffset);
diff --git a/Source/core/rendering/RenderTable.h b/Source/core/rendering/RenderTable.h
index d18b649..bdc1a3d 100644
--- a/Source/core/rendering/RenderTable.h
+++ b/Source/core/rendering/RenderTable.h
@@ -221,7 +221,7 @@
         if (documentBeingDestroyed())
             return;
         m_needsSectionRecalc = true;
-        setNeedsLayout(true);
+        setNeedsLayout();
     }
 
     RenderTableSection* sectionAbove(const RenderTableSection*, SkipEmptySectionsValue = DoNotSkipEmptySections) const;
diff --git a/Source/core/rendering/RenderTableCell.cpp b/Source/core/rendering/RenderTableCell.cpp
index 44316f7..b67203d 100644
--- a/Source/core/rendering/RenderTableCell.cpp
+++ b/Source/core/rendering/RenderTableCell.cpp
@@ -200,7 +200,7 @@
     // FIXME: Changing an intrinsic padding shouldn't trigger a relayout as it only shifts the cell inside the row but
     // doesn't change the logical height.
     if (intrinsicPaddingBefore != oldIntrinsicPaddingBefore || intrinsicPaddingAfter != oldIntrinsicPaddingAfter)
-        setNeedsLayout(true, MarkOnlyThis);
+        setNeedsLayout(MarkOnlyThis);
 }
 
 void RenderTableCell::updateLogicalWidth()
@@ -212,8 +212,8 @@
     if (tableLayoutLogicalWidth == logicalWidth())
         return;
 
-    setNeedsLayout(true, MarkOnlyThis);
-    row()->setChildNeedsLayout(true, MarkOnlyThis);
+    setNeedsLayout(MarkOnlyThis);
+    row()->setChildNeedsLayout(MarkOnlyThis);
 
     if (!table()->selfNeedsLayout() && checkForRepaintDuringLayout())
         repaint();
@@ -237,7 +237,7 @@
     if (isBaselineAligned() && section()->rowBaseline(rowIndex()) && cellBaselinePosition() > section()->rowBaseline(rowIndex())) {
         int newIntrinsicPaddingBefore = max<LayoutUnit>(0, intrinsicPaddingBefore() - max<LayoutUnit>(0, cellBaselinePosition() - oldCellBaseline));
         setIntrinsicPaddingBefore(newIntrinsicPaddingBefore);
-        setNeedsLayout(true, MarkOnlyThis);
+        setNeedsLayout(MarkOnlyThis);
         layoutBlock(cellWidthChanged());
     }
 
diff --git a/Source/core/rendering/RenderTableCol.cpp b/Source/core/rendering/RenderTableCol.cpp
index 533cf48..ce0dd03 100644
--- a/Source/core/rendering/RenderTableCol.cpp
+++ b/Source/core/rendering/RenderTableCol.cpp
@@ -28,7 +28,7 @@
 
 #include "HTMLNames.h"
 #include "core/html/HTMLTableColElement.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/RenderTable.h"
 #include "core/rendering/RenderTableCell.h"
 
diff --git a/Source/core/rendering/RenderTableRow.cpp b/Source/core/rendering/RenderTableRow.cpp
index f6831b2..3fae922 100644
--- a/Source/core/rendering/RenderTableRow.cpp
+++ b/Source/core/rendering/RenderTableRow.cpp
@@ -27,7 +27,7 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderTableCell.h"
@@ -84,7 +84,7 @@
             for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
                 if (!childBox->isTableCell())
                     continue;
-                childBox->setChildNeedsLayout(true, MarkOnlyThis);
+                childBox->setChildNeedsLayout(MarkOnlyThis);
             }
         }
     }
@@ -167,7 +167,7 @@
         if (child->isTableCell()) {
             RenderTableCell* cell = toRenderTableCell(child);
             if (!cell->needsLayout() && paginated && view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(cell, cell->logicalTop()) != cell->pageLogicalOffset())
-                cell->setChildNeedsLayout(true, MarkOnlyThis);
+                cell->setChildNeedsLayout(MarkOnlyThis);
 
             if (child->needsLayout()) {
                 cell->computeAndSetBlockDirectionMargins(table());
@@ -190,7 +190,7 @@
 
     statePusher.pop();
     // RenderTableSection::layoutRows will set our logical height and width later, so it calls updateLayerTransform().
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 LayoutRect RenderTableRow::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
diff --git a/Source/core/rendering/RenderTableSection.cpp b/Source/core/rendering/RenderTableSection.cpp
index 282e7fa..80938cc 100644
--- a/Source/core/rendering/RenderTableSection.cpp
+++ b/Source/core/rendering/RenderTableSection.cpp
@@ -406,15 +406,24 @@
 
         unsigned rowSpan = cell->rowSpan();
 
+        unsigned spanningCellEndIndex = rowIndex + rowSpan;
+        unsigned lastSpanningCellEndIndex = lastRowIndex + lastRowSpan;
+
         // Only heightest spanning cell will distribute it's extra height in row if more then one spanning cells
         // present at same level.
         if (rowIndex == lastRowIndex && rowSpan == lastRowSpan)
             continue;
 
-        int originalBeforePosition = m_rowPos[rowIndex + rowSpan];
+        int originalBeforePosition = m_rowPos[spanningCellEndIndex];
+
+        // When 2 spanning cells are ending at same row index then while extra height distribution of first spanning
+        // cell updates position of the last row so getting the original position of the last row in second spanning
+        // cell need to reduce the height changed by first spanning cell.
+        if (spanningCellEndIndex == lastSpanningCellEndIndex)
+            originalBeforePosition -= extraHeightToPropagate;
 
         if (extraHeightToPropagate) {
-            for (unsigned row = lastRowIndex + lastRowSpan; row <= rowIndex + rowSpan; row++)
+            for (unsigned row = lastSpanningCellEndIndex + 1; row <= spanningCellEndIndex; row++)
                 m_rowPos[row] += extraHeightToPropagate;
         }
 
@@ -436,7 +445,7 @@
         // is distributing it's extra height in rows.
 
         // Calculate total percentage, total auto rows height and total rows height except percent rows.
-        for (unsigned row = rowIndex; row < (rowIndex + rowSpan); row++) {
+        for (unsigned row = rowIndex; row < spanningCellEndIndex; row++) {
             if (m_grid[row].logicalHeight.isPercent()) {
                 totalPercent += m_grid[row].logicalHeight.percent();
                 totalRemainingRowsHeight -= spanningRowsHeight.rowHeight[row - rowIndex];
@@ -454,13 +463,12 @@
         ASSERT(!extraRowSpanningHeight);
 
         // Getting total changed height in the table
-        extraHeightToPropagate = m_rowPos[rowIndex + rowSpan] - originalBeforePosition;
-        m_rowPos[rowIndex + rowSpan] -= extraHeightToPropagate;
+        extraHeightToPropagate = m_rowPos[spanningCellEndIndex] - originalBeforePosition;
     }
 
     if (extraHeightToPropagate) {
         // Apply changed height by rowSpan cells to rows present at the end of the table
-        for (unsigned row = lastRowIndex + lastRowSpan; row <= m_grid.size(); row++)
+        for (unsigned row = lastRowIndex + lastRowSpan + 1; row <= m_grid.size(); row++)
             m_rowPos[row] += extraHeightToPropagate;
     }
 }
@@ -473,13 +481,15 @@
     if (!cell->isBaselineAligned())
         return;
 
-    LayoutUnit baselinePosition = cell->cellBaselinePosition();
-    if (baselinePosition > cell->borderBefore() + cell->paddingBefore()) {
+    // Ignoring the intrinsic padding as it depends on knowing the row's baseline, which won't be accurate
+    // until the end of this function.
+    LayoutUnit baselinePosition = cell->cellBaselinePosition() - cell->intrinsicPaddingBefore();
+    if (baselinePosition > cell->borderBefore() + (cell->paddingBefore() - cell->intrinsicPaddingBefore())) {
         m_grid[row].baseline = max(m_grid[row].baseline, baselinePosition);
 
         int cellStartRowBaselineDescent = 0;
         if (cell->rowSpan() == 1) {
-            baselineDescent = max(baselineDescent, cell->logicalHeightForRowSizing() - (baselinePosition - cell->intrinsicPaddingBefore()));
+            baselineDescent = max(baselineDescent, cell->logicalHeightForRowSizing() - baselinePosition);
             cellStartRowBaselineDescent = baselineDescent;
         }
         m_rowPos[row + 1] = max<int>(m_rowPos[row + 1], m_rowPos[row] + m_grid[row].baseline + cellStartRowBaselineDescent);
@@ -629,7 +639,7 @@
     }
 
     statePusher.pop();
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderTableSection::distributeExtraLogicalHeightToPercentRows(int& extraLogicalHeight, int totalPercent)
@@ -789,7 +799,7 @@
                 if (!o->isText() && o->style()->logicalHeight().isPercent() && (flexAllChildren || o->isReplaced() || (o->isBox() && toRenderBox(o)->scrollsOverflow()))) {
                     // Tables with no sections do not flex.
                     if (!o->isTable() || toRenderTable(o)->hasSections()) {
-                        o->setNeedsLayout(true, MarkOnlyThis);
+                        o->setNeedsLayout(MarkOnlyThis);
                         cellChildrenFlex = true;
                     }
                 }
@@ -805,7 +815,7 @@
                     while (box != cell) {
                         if (box->normalChildNeedsLayout())
                             break;
-                        box->setChildNeedsLayout(true, MarkOnlyThis);
+                        box->setChildNeedsLayout(MarkOnlyThis);
                         box = box->containingBlock();
                         ASSERT(box);
                         if (!box)
@@ -837,7 +847,7 @@
             setLogicalPositionForCell(cell, c);
 
             if (!cell->needsLayout() && view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(cell, cell->logicalTop()) != cell->pageLogicalOffset())
-                cell->setChildNeedsLayout(true, MarkOnlyThis);
+                cell->setChildNeedsLayout(MarkOnlyThis);
 
             cell->layoutIfNeeded();
 
@@ -1164,7 +1174,7 @@
     LayoutPoint adjustedPaintOffset = paintOffset + location();
 
     PaintPhase phase = paintInfo.phase;
-    bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
+    bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset, ForceContentsClip);
     paintObject(paintInfo, adjustedPaintOffset);
     if (pushedClip)
         popContentsClip(paintInfo, phase, adjustedPaintOffset);
@@ -1466,7 +1476,7 @@
     }
 
     m_grid.shrinkToFit();
-    setNeedsLayout(true);
+    setNeedsLayout();
 }
 
 // FIXME: This function could be made O(1) in certain cases (like for the non-most-constrainive cells' case).
diff --git a/Source/core/rendering/RenderText.cpp b/Source/core/rendering/RenderText.cpp
index 94a73bf..56135c0 100644
--- a/Source/core/rendering/RenderText.cpp
+++ b/Source/core/rendering/RenderText.cpp
@@ -41,6 +41,7 @@
 #include "core/rendering/RenderView.h"
 #include "core/rendering/break_lines.h"
 #include "wtf/text/StringBuffer.h"
+#include "wtf/text/StringBuilder.h"
 #include "wtf/unicode/CharacterNames.h"
 
 using namespace std;
diff --git a/Source/core/rendering/RenderTextControl.cpp b/Source/core/rendering/RenderTextControl.cpp
index 5ca4fd8..aaac50e 100644
--- a/Source/core/rendering/RenderTextControl.cpp
+++ b/Source/core/rendering/RenderTextControl.cpp
@@ -283,7 +283,7 @@
         // The markParents arguments should be false because this function is
         // called from layout() of the parent and the placeholder layout doesn't
         // affect the parent layout.
-        placeholderRenderer->setChildNeedsLayout(true, MarkOnlyThis);
+        placeholderRenderer->setChildNeedsLayout(MarkOnlyThis);
     }
     return placeholderRenderer;
 }
diff --git a/Source/core/rendering/RenderTextControlSingleLine.cpp b/Source/core/rendering/RenderTextControlSingleLine.cpp
index de649d4..08b9501 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.cpp
+++ b/Source/core/rendering/RenderTextControlSingleLine.cpp
@@ -92,7 +92,7 @@
     ASSERT(start);
     ASSERT(start != end);
     for (RenderObject* renderer = start; renderer != end; renderer = renderer->parent())
-        renderer->setNeedsLayout(true, MarkOnlyThis);
+        renderer->setNeedsLayout(MarkOnlyThis);
 }
 
 void RenderTextControlSingleLine::layout()
@@ -133,15 +133,15 @@
     LayoutUnit logicalHeightLimit = computeLogicalHeightLimit();
     if (innerTextRenderer && innerTextRenderer->logicalHeight() > logicalHeightLimit) {
         if (desiredLogicalHeight != innerTextRenderer->logicalHeight())
-            setNeedsLayout(true, MarkOnlyThis);
+            setNeedsLayout(MarkOnlyThis);
 
         m_desiredInnerTextLogicalHeight = desiredLogicalHeight;
 
         innerTextRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
-        innerTextRenderer->setNeedsLayout(true, MarkOnlyThis);
+        innerTextRenderer->setNeedsLayout(MarkOnlyThis);
         if (innerBlockRenderer) {
             innerBlockRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
-            innerBlockRenderer->setNeedsLayout(true, MarkOnlyThis);
+            innerBlockRenderer->setNeedsLayout(MarkOnlyThis);
         }
     }
     // The container might be taller because of decoration elements.
@@ -150,10 +150,10 @@
         LayoutUnit containerLogicalHeight = containerRenderer->logicalHeight();
         if (containerLogicalHeight > logicalHeightLimit) {
             containerRenderer->style()->setLogicalHeight(Length(logicalHeightLimit, Fixed));
-            setNeedsLayout(true, MarkOnlyThis);
+            setNeedsLayout(MarkOnlyThis);
         } else if (containerRenderer->logicalHeight() < contentLogicalHeight()) {
             containerRenderer->style()->setLogicalHeight(Length(contentLogicalHeight(), Fixed));
-            setNeedsLayout(true, MarkOnlyThis);
+            setNeedsLayout(MarkOnlyThis);
         } else
             containerRenderer->style()->setLogicalHeight(Length(containerLogicalHeight, Fixed));
     }
@@ -252,7 +252,7 @@
     }
     RenderObject* innerTextRenderer = innerTextElement()->renderer();
     if (innerTextRenderer && diff == StyleDifferenceLayout)
-        innerTextRenderer->setNeedsLayout(true, MarkContainingBlockChain);
+        innerTextRenderer->setNeedsLayout(MarkContainingBlockChain);
     if (HTMLElement* placeholder = inputElement()->placeholderElement())
         placeholder->setInlineStyleProperty(CSSPropertyTextOverflow, textShouldBeTruncated() ? CSSValueEllipsis : CSSValueClip);
     setHasOverflowClip(false);
diff --git a/Source/core/rendering/RenderTheme.cpp b/Source/core/rendering/RenderTheme.cpp
index 0150f98..0e4903c 100644
--- a/Source/core/rendering/RenderTheme.cpp
+++ b/Source/core/rendering/RenderTheme.cpp
@@ -802,15 +802,11 @@
     if (!node)
         return false;
 
-    Frame* frame = node->document()->frame();
-    if (!frame)
-        return false;
-
-    Page* page = frame->page();
+    Page* page = node->document()->page();
     if (!page)
         return false;
 
-    return page->focusController()->isActive();
+    return page->focusController().isActive();
 }
 
 bool RenderTheme::isChecked(const RenderObject* o) const
diff --git a/Source/core/rendering/RenderThemeChromiumFontProvider.cpp b/Source/core/rendering/RenderThemeChromiumFontProvider.cpp
index 81623a2..527f855 100644
--- a/Source/core/rendering/RenderThemeChromiumFontProvider.cpp
+++ b/Source/core/rendering/RenderThemeChromiumFontProvider.cpp
@@ -48,7 +48,7 @@
 // sizes (e.g. 15px). So, for now we just use Arial.
 const String& RenderThemeChromiumFontProvider::defaultGUIFont()
 {
-    DEFINE_STATIC_LOCAL(String, fontFace, (ASCIILiteral("Arial")));
+    DEFINE_STATIC_LOCAL(String, fontFace, ("Arial"));
     return fontFace;
 }
 
diff --git a/Source/core/rendering/RenderVideo.cpp b/Source/core/rendering/RenderVideo.cpp
index 580bbf3..62e8ac2 100644
--- a/Source/core/rendering/RenderVideo.cpp
+++ b/Source/core/rendering/RenderVideo.cpp
@@ -81,7 +81,7 @@
 
     setIntrinsicSize(size);
     setPreferredLogicalWidthsDirty(true);
-    setNeedsLayout(true);
+    setNeedsLayout();
 }
 
 LayoutSize RenderVideo::calculateIntrinsicSize()
diff --git a/Source/core/rendering/RenderView.cpp b/Source/core/rendering/RenderView.cpp
index 12b102b..b71d4fe 100644
--- a/Source/core/rendering/RenderView.cpp
+++ b/Source/core/rendering/RenderView.cpp
@@ -119,7 +119,7 @@
 void RenderView::markLazyBlocksForLayout()
 {
     for (RenderLazyBlock* block = m_firstLazyBlock; block; block = block->next())
-        block->setNeedsLayout(true);
+        block->setNeedsLayout();
 }
 
 void RenderView::layoutContent(const LayoutState& state)
@@ -260,7 +260,7 @@
     // Use calcWidth/Height to get the new width/height, since this will take the full page zoom factor into account.
     bool relayoutChildren = !shouldUsePrintingLayout() && (!m_frameView || width() != viewWidth() || height() != viewHeight());
     if (relayoutChildren) {
-        setChildNeedsLayout(true, MarkOnlyThis);
+        setChildNeedsLayout(MarkOnlyThis);
         for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
             if ((child->isBox() && toRenderBox(child)->hasRelativeLogicalHeight())
                     || child->style()->logicalHeight().isPercent()
@@ -270,7 +270,7 @@
                     || child->style()->logicalMinHeight().isViewportPercentage()
                     || child->style()->logicalMaxHeight().isViewportPercentage()
                     || child->isSVGRoot())
-                child->setChildNeedsLayout(true, MarkOnlyThis);
+                child->setChildNeedsLayout(MarkOnlyThis);
         }
     }
 
@@ -293,7 +293,7 @@
     checkLayoutState(state);
 #endif
     m_layoutState = 0;
-    setNeedsLayout(false);
+    clearNeedsLayout();
 
     if (isSeamlessAncestorInFlowThread)
         flowThreadController()->setCurrentRenderFlowThread(0);
diff --git a/Source/core/rendering/RenderWidget.cpp b/Source/core/rendering/RenderWidget.cpp
index 8879ab2..7b73394 100644
--- a/Source/core/rendering/RenderWidget.cpp
+++ b/Source/core/rendering/RenderWidget.cpp
@@ -207,7 +207,7 @@
     StackStats::LayoutCheckPoint layoutCheckPoint;
     ASSERT(needsLayout());
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderWidget::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
diff --git a/Source/core/rendering/style/RenderStyle.h b/Source/core/rendering/style/RenderStyle.h
index b4c6a66..7d97ea9 100644
--- a/Source/core/rendering/style/RenderStyle.h
+++ b/Source/core/rendering/style/RenderStyle.h
@@ -1319,6 +1319,8 @@
     void setStrokeOpacity(float f) { accessSVGStyle()->setStrokeOpacity(f); }
     SVGLength strokeWidth() const { return svgStyle()->strokeWidth(); }
     void setStrokeWidth(SVGLength w) { accessSVGStyle()->setStrokeWidth(w); }
+    Vector<SVGLength> strokeDashArray() const { return svgStyle()->strokeDashArray(); }
+    void setStrokeDashArray(Vector<SVGLength> array) { accessSVGStyle()->setStrokeDashArray(array); }
     SVGLength strokeDashOffset() const { return svgStyle()->strokeDashOffset(); }
     void setStrokeDashOffset(SVGLength d) { accessSVGStyle()->setStrokeDashOffset(d); }
     float strokeMiterLimit() const { return svgStyle()->strokeMiterLimit(); }
diff --git a/Source/core/rendering/style/StyleCustomFilterProgram.h b/Source/core/rendering/style/StyleCustomFilterProgram.h
index 1581a2f..1678217 100644
--- a/Source/core/rendering/style/StyleCustomFilterProgram.h
+++ b/Source/core/rendering/style/StyleCustomFilterProgram.h
@@ -30,9 +30,9 @@
 #ifndef StyleCustomFilterProgram_h
 #define StyleCustomFilterProgram_h
 
-#include "core/loader/cache/CachedShader.h"
 #include "core/loader/cache/ResourceClient.h"
 #include "core/loader/cache/ResourcePtr.h"
+#include "core/loader/cache/ShaderResource.h"
 #include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
 #include "core/rendering/style/StyleShader.h"
 #include "weborigin/KURL.h"
@@ -86,8 +86,8 @@
     {
         // Do not use the Resource:isLoaded method here, because it actually means !isLoading(),
         // so missing and canceled resources will have isLoaded set to true, even if they are not loaded yet.
-        ASSERT(!m_vertexShader || m_vertexShader->isCachedShader());
-        ASSERT(!m_fragmentShader || m_fragmentShader->isCachedShader());
+        ASSERT(!m_vertexShader || m_vertexShader->isShaderResource());
+        ASSERT(!m_fragmentShader || m_fragmentShader->isShaderResource());
         ASSERT(m_cachedVertexShader.get() || m_cachedFragmentShader.get());
         return (!m_cachedVertexShader.get() || m_isVertexShaderLoaded)
             && (!m_cachedFragmentShader.get() || m_isFragmentShaderLoaded);
@@ -96,11 +96,11 @@
     virtual void willHaveClients()
     {
         if (m_vertexShader) {
-            m_cachedVertexShader = m_vertexShader->cachedShader();
+            m_cachedVertexShader = m_vertexShader->resource();
             m_cachedVertexShader->addClient(this);
         }
         if (m_fragmentShader) {
-            m_cachedFragmentShader = m_fragmentShader->cachedShader();
+            m_cachedFragmentShader = m_fragmentShader->resource();
             m_cachedFragmentShader->addClient(this);
         }
     }
@@ -164,8 +164,8 @@
     RefPtr<StyleShader> m_vertexShader;
     RefPtr<StyleShader> m_fragmentShader;
 
-    ResourcePtr<CachedShader> m_cachedVertexShader;
-    ResourcePtr<CachedShader> m_cachedFragmentShader;
+    ResourcePtr<ShaderResource> m_cachedVertexShader;
+    ResourcePtr<ShaderResource> m_cachedFragmentShader;
 
     // The URLs form the key of the StyleCustomFilterProgram in the cache and are used
     // to lookup the StyleCustomFilterProgram when it's removed from the cache.
diff --git a/Source/core/rendering/style/StyleCachedImage.cpp b/Source/core/rendering/style/StyleFetchedImage.cpp
similarity index 61%
rename from Source/core/rendering/style/StyleCachedImage.cpp
rename to Source/core/rendering/style/StyleFetchedImage.cpp
index 76e90e2..e094475 100644
--- a/Source/core/rendering/style/StyleCachedImage.cpp
+++ b/Source/core/rendering/style/StyleFetchedImage.cpp
@@ -22,91 +22,91 @@
  */
 
 #include "config.h"
-#include "core/rendering/style/StyleCachedImage.h"
+#include "core/rendering/style/StyleFetchedImage.h"
 
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/RenderObject.h"
 
 namespace WebCore {
 
-StyleCachedImage::StyleCachedImage(CachedImage* image)
+StyleFetchedImage::StyleFetchedImage(ImageResource* image)
     : m_image(image)
 {
-    m_isCachedImage = true;
+    m_isImageResource = true;
     m_image->addClient(this);
 }
 
-StyleCachedImage::~StyleCachedImage()
+StyleFetchedImage::~StyleFetchedImage()
 {
     m_image->removeClient(this);
 }
 
-PassRefPtr<CSSValue> StyleCachedImage::cssValue() const
+PassRefPtr<CSSValue> StyleFetchedImage::cssValue() const
 {
     return CSSPrimitiveValue::create(m_image->url().string(), CSSPrimitiveValue::CSS_URI);
 }
 
-bool StyleCachedImage::canRender(const RenderObject* renderer, float multiplier) const
+bool StyleFetchedImage::canRender(const RenderObject* renderer, float multiplier) const
 {
     return m_image->canRender(renderer, multiplier);
 }
 
-bool StyleCachedImage::isLoaded() const
+bool StyleFetchedImage::isLoaded() const
 {
     return m_image->isLoaded();
 }
 
-bool StyleCachedImage::errorOccurred() const
+bool StyleFetchedImage::errorOccurred() const
 {
     return m_image->errorOccurred();
 }
 
-LayoutSize StyleCachedImage::imageSize(const RenderObject* renderer, float multiplier) const
+LayoutSize StyleFetchedImage::imageSize(const RenderObject* renderer, float multiplier) const
 {
     return m_image->imageSizeForRenderer(renderer, multiplier);
 }
 
-bool StyleCachedImage::imageHasRelativeWidth() const
+bool StyleFetchedImage::imageHasRelativeWidth() const
 {
     return m_image->imageHasRelativeWidth();
 }
 
-bool StyleCachedImage::imageHasRelativeHeight() const
+bool StyleFetchedImage::imageHasRelativeHeight() const
 {
     return m_image->imageHasRelativeHeight();
 }
 
-void StyleCachedImage::computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
+void StyleFetchedImage::computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
 {
     m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
 }
 
-bool StyleCachedImage::usesImageContainerSize() const
+bool StyleFetchedImage::usesImageContainerSize() const
 {
     return m_image->usesImageContainerSize();
 }
 
-void StyleCachedImage::setContainerSizeForRenderer(const RenderObject* renderer, const IntSize& imageContainerSize, float imageContainerZoomFactor)
+void StyleFetchedImage::setContainerSizeForRenderer(const RenderObject* renderer, const IntSize& imageContainerSize, float imageContainerZoomFactor)
 {
     m_image->setContainerSizeForRenderer(renderer, imageContainerSize, imageContainerZoomFactor);
 }
 
-void StyleCachedImage::addClient(RenderObject* renderer)
+void StyleFetchedImage::addClient(RenderObject* renderer)
 {
     m_image->addClient(renderer);
 }
 
-void StyleCachedImage::removeClient(RenderObject* renderer)
+void StyleFetchedImage::removeClient(RenderObject* renderer)
 {
     m_image->removeClient(renderer);
 }
 
-PassRefPtr<Image> StyleCachedImage::image(RenderObject* renderer, const IntSize&) const
+PassRefPtr<Image> StyleFetchedImage::image(RenderObject* renderer, const IntSize&) const
 {
     return m_image->imageForRenderer(renderer);
 }
 
-bool StyleCachedImage::knownToBeOpaque(const RenderObject* renderer) const
+bool StyleFetchedImage::knownToBeOpaque(const RenderObject* renderer) const
 {
     return m_image->currentFrameKnownToBeOpaque(renderer);
 }
diff --git a/Source/core/rendering/style/StyleCachedImage.h b/Source/core/rendering/style/StyleFetchedImage.h
similarity index 80%
rename from Source/core/rendering/style/StyleCachedImage.h
rename to Source/core/rendering/style/StyleFetchedImage.h
index 806357d..b9effd9 100644
--- a/Source/core/rendering/style/StyleCachedImage.h
+++ b/Source/core/rendering/style/StyleFetchedImage.h
@@ -21,22 +21,22 @@
  *
  */
 
-#ifndef StyleCachedImage_h
-#define StyleCachedImage_h
+#ifndef StyleFetchedImage_h
+#define StyleFetchedImage_h
 
-#include "core/loader/cache/CachedImageClient.h"
+#include "core/loader/cache/ImageResourceClient.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/rendering/style/StyleImage.h"
 
 namespace WebCore {
 
-class CachedImage;
+class ImageResource;
 
-class StyleCachedImage : public StyleImage, private CachedImageClient {
+class StyleFetchedImage : public StyleImage, private ImageResourceClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassRefPtr<StyleCachedImage> create(CachedImage* image) { return adoptRef(new StyleCachedImage(image)); }
-    virtual ~StyleCachedImage();
+    static PassRefPtr<StyleFetchedImage> create(ImageResource* image) { return adoptRef(new StyleFetchedImage(image)); }
+    virtual ~StyleFetchedImage();
 
     virtual WrappedImagePtr data() const { return m_image.get(); }
 
@@ -55,12 +55,12 @@
     virtual void removeClient(RenderObject*);
     virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const;
     virtual bool knownToBeOpaque(const RenderObject*) const OVERRIDE;
-    virtual CachedImage* cachedImage() const OVERRIDE { return m_image.get(); }
+    virtual ImageResource* cachedImage() const OVERRIDE { return m_image.get(); }
 
 private:
-    explicit StyleCachedImage(CachedImage*);
+    explicit StyleFetchedImage(ImageResource*);
 
-    ResourcePtr<CachedImage> m_image;
+    ResourcePtr<ImageResource> m_image;
 };
 
 }
diff --git a/Source/core/rendering/style/StyleCachedImageSet.cpp b/Source/core/rendering/style/StyleFetchedImageSet.cpp
similarity index 65%
rename from Source/core/rendering/style/StyleCachedImageSet.cpp
rename to Source/core/rendering/style/StyleFetchedImageSet.cpp
index 127f3f1..b9e9d52 100644
--- a/Source/core/rendering/style/StyleCachedImageSet.cpp
+++ b/Source/core/rendering/style/StyleFetchedImageSet.cpp
@@ -24,97 +24,97 @@
  */
 
 #include "config.h"
-#include "core/rendering/style/StyleCachedImageSet.h"
+#include "core/rendering/style/StyleFetchedImageSet.h"
 
 #include "core/css/CSSImageSetValue.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/rendering/RenderObject.h"
 
 namespace WebCore {
 
-StyleCachedImageSet::StyleCachedImageSet(CachedImage* image, float imageScaleFactor, CSSImageSetValue* value)
+StyleFetchedImageSet::StyleFetchedImageSet(ImageResource* image, float imageScaleFactor, CSSImageSetValue* value)
     : m_bestFitImage(image)
     , m_imageScaleFactor(imageScaleFactor)
     , m_imageSetValue(value)
 {
-    m_isCachedImageSet = true;
+    m_isImageResourceSet = true;
     m_bestFitImage->addClient(this);
 }
 
 
-StyleCachedImageSet::~StyleCachedImageSet()
+StyleFetchedImageSet::~StyleFetchedImageSet()
 {
     m_bestFitImage->removeClient(this);
 }
 
-PassRefPtr<CSSValue> StyleCachedImageSet::cssValue() const
+PassRefPtr<CSSValue> StyleFetchedImageSet::cssValue() const
 {
     return m_imageSetValue;
 }
 
-bool StyleCachedImageSet::canRender(const RenderObject* renderer, float multiplier) const
+bool StyleFetchedImageSet::canRender(const RenderObject* renderer, float multiplier) const
 {
     return m_bestFitImage->canRender(renderer, multiplier);
 }
 
-bool StyleCachedImageSet::isLoaded() const
+bool StyleFetchedImageSet::isLoaded() const
 {
     return m_bestFitImage->isLoaded();
 }
 
-bool StyleCachedImageSet::errorOccurred() const
+bool StyleFetchedImageSet::errorOccurred() const
 {
     return m_bestFitImage->errorOccurred();
 }
 
-LayoutSize StyleCachedImageSet::imageSize(const RenderObject* renderer, float multiplier) const
+LayoutSize StyleFetchedImageSet::imageSize(const RenderObject* renderer, float multiplier) const
 {
     LayoutSize scaledImageSize = m_bestFitImage->imageSizeForRenderer(renderer, multiplier);
     scaledImageSize.scale(1 / m_imageScaleFactor);
     return scaledImageSize;
 }
 
-bool StyleCachedImageSet::imageHasRelativeWidth() const
+bool StyleFetchedImageSet::imageHasRelativeWidth() const
 {
     return m_bestFitImage->imageHasRelativeWidth();
 }
 
-bool StyleCachedImageSet::imageHasRelativeHeight() const
+bool StyleFetchedImageSet::imageHasRelativeHeight() const
 {
     return m_bestFitImage->imageHasRelativeHeight();
 }
 
-void StyleCachedImageSet::computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
+void StyleFetchedImageSet::computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
 {
     m_bestFitImage->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
 }
 
-bool StyleCachedImageSet::usesImageContainerSize() const
+bool StyleFetchedImageSet::usesImageContainerSize() const
 {
     return m_bestFitImage->usesImageContainerSize();
 }
 
-void StyleCachedImageSet::setContainerSizeForRenderer(const RenderObject* renderer, const IntSize& imageContainerSize, float imageContainerZoomFactor)
+void StyleFetchedImageSet::setContainerSizeForRenderer(const RenderObject* renderer, const IntSize& imageContainerSize, float imageContainerZoomFactor)
 {
     m_bestFitImage->setContainerSizeForRenderer(renderer, imageContainerSize, imageContainerZoomFactor);
 }
 
-void StyleCachedImageSet::addClient(RenderObject* renderer)
+void StyleFetchedImageSet::addClient(RenderObject* renderer)
 {
     m_bestFitImage->addClient(renderer);
 }
 
-void StyleCachedImageSet::removeClient(RenderObject* renderer)
+void StyleFetchedImageSet::removeClient(RenderObject* renderer)
 {
     m_bestFitImage->removeClient(renderer);
 }
 
-PassRefPtr<Image> StyleCachedImageSet::image(RenderObject* renderer, const IntSize&) const
+PassRefPtr<Image> StyleFetchedImageSet::image(RenderObject* renderer, const IntSize&) const
 {
     return m_bestFitImage->imageForRenderer(renderer);
 }
 
-bool StyleCachedImageSet::knownToBeOpaque(const RenderObject* renderer) const
+bool StyleFetchedImageSet::knownToBeOpaque(const RenderObject* renderer) const
 {
     return m_bestFitImage->currentFrameKnownToBeOpaque(renderer);
 }
diff --git a/Source/core/rendering/style/StyleCachedImageSet.h b/Source/core/rendering/style/StyleFetchedImageSet.h
similarity index 81%
rename from Source/core/rendering/style/StyleCachedImageSet.h
rename to Source/core/rendering/style/StyleFetchedImageSet.h
index c90b5e7..3e431e2 100644
--- a/Source/core/rendering/style/StyleCachedImageSet.h
+++ b/Source/core/rendering/style/StyleFetchedImageSet.h
@@ -23,29 +23,29 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef StyleCachedImageSet_h
-#define StyleCachedImageSet_h
+#ifndef StyleFetchedImageSet_h
+#define StyleFetchedImageSet_h
 
-#include "core/loader/cache/CachedImageClient.h"
+#include "core/loader/cache/ImageResourceClient.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/graphics/LayoutSize.h"
 #include "core/rendering/style/StyleImage.h"
 
 namespace WebCore {
 
-class CachedImage;
+class ImageResource;
 class CSSImageSetValue;
 
 // This class keeps one cached image and has access to a set of alternatives.
 
-class StyleCachedImageSet : public StyleImage, private CachedImageClient {
+class StyleFetchedImageSet : public StyleImage, private ImageResourceClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassRefPtr<StyleCachedImageSet> create(CachedImage* image, float imageScaleFactor, CSSImageSetValue* value)
+    static PassRefPtr<StyleFetchedImageSet> create(ImageResource* image, float imageScaleFactor, CSSImageSetValue* value)
     {
-        return adoptRef(new StyleCachedImageSet(image, imageScaleFactor, value));
+        return adoptRef(new StyleFetchedImageSet(image, imageScaleFactor, value));
     }
-    virtual ~StyleCachedImageSet();
+    virtual ~StyleFetchedImageSet();
 
     virtual PassRefPtr<CSSValue> cssValue() const;
 
@@ -70,16 +70,16 @@
     virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const;
     virtual float imageScaleFactor() const { return m_imageScaleFactor; }
     virtual bool knownToBeOpaque(const RenderObject*) const OVERRIDE;
-    virtual CachedImage* cachedImage() const OVERRIDE { return m_bestFitImage.get(); }
+    virtual ImageResource* cachedImage() const OVERRIDE { return m_bestFitImage.get(); }
 
 private:
-    StyleCachedImageSet(CachedImage*, float imageScaleFactor, CSSImageSetValue*);
+    StyleFetchedImageSet(ImageResource*, float imageScaleFactor, CSSImageSetValue*);
 
-    ResourcePtr<CachedImage> m_bestFitImage;
+    ResourcePtr<ImageResource> m_bestFitImage;
     float m_imageScaleFactor;
     CSSImageSetValue* m_imageSetValue; // Not retained; it owns us.
 };
 
 } // namespace WebCore
 
-#endif // StyleCachedImageSet_h
+#endif // StyleFetchedImageSet_h
diff --git a/Source/core/rendering/style/StyleCachedShader.cpp b/Source/core/rendering/style/StyleFetchedShader.cpp
similarity index 86%
rename from Source/core/rendering/style/StyleCachedShader.cpp
rename to Source/core/rendering/style/StyleFetchedShader.cpp
index f01ddcf..2b6c6c2 100644
--- a/Source/core/rendering/style/StyleCachedShader.cpp
+++ b/Source/core/rendering/style/StyleFetchedShader.cpp
@@ -29,21 +29,21 @@
 
 #include "config.h"
 
-#include "core/rendering/style/StyleCachedShader.h"
+#include "core/rendering/style/StyleFetchedShader.h"
 
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/loader/cache/CachedShader.h"
+#include "core/loader/cache/ShaderResource.h"
 
 namespace WebCore {
 
 
-StyleCachedShader::StyleCachedShader(CachedShader* shader)
+StyleFetchedShader::StyleFetchedShader(ShaderResource* shader)
     : m_shader(shader)
 {
-     m_isCachedShader = true;
+    m_isShaderResource = true;
 }
 
-PassRefPtr<CSSValue> StyleCachedShader::cssValue() const
+PassRefPtr<CSSValue> StyleFetchedShader::cssValue() const
 {
     return CSSPrimitiveValue::create(m_shader->url().string(), CSSPrimitiveValue::CSS_URI);
 }
diff --git a/Source/core/rendering/style/StyleCachedShader.h b/Source/core/rendering/style/StyleFetchedShader.h
similarity index 75%
rename from Source/core/rendering/style/StyleCachedShader.h
rename to Source/core/rendering/style/StyleFetchedShader.h
index 739f349..88e5411 100644
--- a/Source/core/rendering/style/StyleCachedShader.h
+++ b/Source/core/rendering/style/StyleFetchedShader.h
@@ -27,31 +27,31 @@
  * SUCH DAMAGE.
  */
 
-#ifndef StyleCachedShader_h
-#define StyleCachedShader_h
+#ifndef StyleFetchedShader_h
+#define StyleFetchedShader_h
 
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/rendering/style/StyleShader.h"
 
 namespace WebCore {
 
-class CachedShader;
+class ShaderResource;
 
-class StyleCachedShader : public StyleShader {
+class StyleFetchedShader : public StyleShader {
 public:
-    // FIXME: Keep a reference to the actual CachedShader in this class.
-    static PassRefPtr<StyleCachedShader> create(CachedShader* shader) { return adoptRef(new StyleCachedShader(shader)); }
+    // FIXME: Keep a reference to the actual ShaderResource in this class.
+    static PassRefPtr<StyleFetchedShader> create(ShaderResource* shader) { return adoptRef(new StyleFetchedShader(shader)); }
 
     virtual PassRefPtr<CSSValue> cssValue() const;
 
-    virtual CachedShader* cachedShader() const { return m_shader.get(); }
+    virtual ShaderResource* resource() const { return m_shader.get(); }
 
 private:
-    StyleCachedShader(CachedShader*);
+    StyleFetchedShader(ShaderResource*);
 
-    ResourcePtr<CachedShader> m_shader;
+    ResourcePtr<ShaderResource> m_shader;
 };
 
 }
 
-#endif // StyleCachedShader_h
+#endif // StyleFetchedShader_h
diff --git a/Source/core/rendering/style/StyleImage.h b/Source/core/rendering/style/StyleImage.h
index 58f0908..e440c22 100644
--- a/Source/core/rendering/style/StyleImage.h
+++ b/Source/core/rendering/style/StyleImage.h
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-class CachedImage;
+class ImageResource;
 class CSSValue;
 class RenderObject;
 
@@ -66,12 +66,12 @@
     virtual WrappedImagePtr data() const = 0;
     virtual float imageScaleFactor() const { return 1; }
     virtual bool knownToBeOpaque(const RenderObject*) const = 0;
-    virtual CachedImage* cachedImage() const { return 0; }
+    virtual ImageResource* cachedImage() const { return 0; }
 
-    ALWAYS_INLINE bool isCachedImage() const { return m_isCachedImage; }
+    ALWAYS_INLINE bool isImageResource() const { return m_isImageResource; }
     ALWAYS_INLINE bool isPendingImage() const { return m_isPendingImage; }
     ALWAYS_INLINE bool isGeneratedImage() const { return m_isGeneratedImage; }
-    ALWAYS_INLINE bool isCachedImageSet() const { return m_isCachedImageSet; }
+    ALWAYS_INLINE bool isImageResourceSet() const { return m_isImageResourceSet; }
 
     static bool imagesEquivalent(const StyleImage* image1, const StyleImage* image2)
     {
@@ -85,16 +85,16 @@
 
 protected:
     StyleImage()
-        : m_isCachedImage(false)
+        : m_isImageResource(false)
         , m_isPendingImage(false)
         , m_isGeneratedImage(false)
-        , m_isCachedImageSet(false)
+        , m_isImageResourceSet(false)
     {
     }
-    bool m_isCachedImage:1;
+    bool m_isImageResource:1;
     bool m_isPendingImage:1;
     bool m_isGeneratedImage:1;
-    bool m_isCachedImageSet:1;
+    bool m_isImageResourceSet:1;
 };
 
 }
diff --git a/Source/core/rendering/style/StylePendingImage.h b/Source/core/rendering/style/StylePendingImage.h
index 9f7bc2a..3633d15 100644
--- a/Source/core/rendering/style/StylePendingImage.h
+++ b/Source/core/rendering/style/StylePendingImage.h
@@ -43,10 +43,10 @@
 public:
     static PassRefPtr<StylePendingImage> create(CSSValue* value) { return adoptRef(new StylePendingImage(value)); }
 
-    virtual WrappedImagePtr data() const { return static_cast<CSSImageValue*>(m_value); }
+    virtual WrappedImagePtr data() const { return m_value; }
 
     virtual PassRefPtr<CSSValue> cssValue() const { return m_value; }
-    CSSImageValue* cssImageValue() const { return m_value->isImageValue() ? static_cast<CSSImageValue*>(m_value) : 0; }
+    CSSImageValue* cssImageValue() const { return m_value->isImageValue() ? toCSSImageValue(m_value) : 0; }
     CSSImageGeneratorValue* cssImageGeneratorValue() const { return m_value->isImageGeneratorValue() ? static_cast<CSSImageGeneratorValue*>(m_value) : 0; }
     CSSCursorImageValue* cssCursorImageValue() const { return m_value->isCursorImageValue() ? static_cast<CSSCursorImageValue*>(m_value) : 0; }
     CSSImageSetValue* cssImageSetValue() const { return m_value->isImageSetValue() ? static_cast<CSSImageSetValue*>(m_value) : 0; }
diff --git a/Source/core/rendering/style/StyleShader.h b/Source/core/rendering/style/StyleShader.h
index de43941..c5927e6 100644
--- a/Source/core/rendering/style/StyleShader.h
+++ b/Source/core/rendering/style/StyleShader.h
@@ -34,27 +34,27 @@
 
 namespace WebCore {
 
-class CachedShader;
+class ShaderResource;
 class CSSValue;
 
 class StyleShader : public RefCounted<StyleShader> {
 public:
     virtual ~StyleShader() { }
 
-    ALWAYS_INLINE bool isCachedShader() const { return m_isCachedShader; }
+    ALWAYS_INLINE bool isShaderResource() const { return m_isShaderResource; }
     ALWAYS_INLINE bool isPendingShader() const { return m_isPendingShader; }
 
     virtual PassRefPtr<CSSValue> cssValue() const = 0;
 
-    virtual CachedShader* cachedShader() const { return 0; }
+    virtual ShaderResource* resource() const { return 0; }
 
 protected:
     StyleShader()
-        : m_isCachedShader(false)
+        : m_isShaderResource(false)
         , m_isPendingShader(false)
     {
     }
-    bool m_isCachedShader : 1;
+    bool m_isShaderResource : 1;
     bool m_isPendingShader : 1;
 };
 
diff --git a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
index 11ce00e..ab598e3 100644
--- a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
+++ b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
@@ -33,8 +33,8 @@
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/dom/Element.h"
-#include "core/loader/cache/CachedDocument.h"
-#include "core/loader/cache/CachedSVGDocumentReference.h"
+#include "core/loader/cache/DocumentResource.h"
+#include "core/loader/cache/DocumentResourceReference.h"
 #include "core/platform/graphics/filters/FilterEffect.h"
 #include "core/platform/graphics/filters/SourceAlpha.h"
 #include "core/rendering/svg/RenderSVGResourceFilter.h"
@@ -92,8 +92,8 @@
     Document* document = renderer->document();
     ASSERT(document);
 
-    CachedSVGDocumentReference* cachedSVGDocumentReference = filterOperation->cachedSVGDocumentReference();
-    CachedDocument* cachedSVGDocument = cachedSVGDocumentReference ? cachedSVGDocumentReference->document() : 0;
+    DocumentResourceReference* documentResourceReference = filterOperation->documentResourceReference();
+    DocumentResource* cachedSVGDocument = documentResourceReference ? documentResourceReference->document() : 0;
 
     // If we have an SVG document, this is an external reference. Otherwise
     // we look up the referenced node in the current document.
diff --git a/Source/core/rendering/svg/RenderSVGContainer.cpp b/Source/core/rendering/svg/RenderSVGContainer.cpp
index d64aec4..3e6ea82 100644
--- a/Source/core/rendering/svg/RenderSVGContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGContainer.cpp
@@ -81,7 +81,7 @@
     }
 
     repainter.repaintAfterLayout();
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderSVGContainer::addChild(RenderObject* child, RenderObject* beforeChild)
diff --git a/Source/core/rendering/svg/RenderSVGGradientStop.cpp b/Source/core/rendering/svg/RenderSVGGradientStop.cpp
index f490629..1cada34 100644
--- a/Source/core/rendering/svg/RenderSVGGradientStop.cpp
+++ b/Source/core/rendering/svg/RenderSVGGradientStop.cpp
@@ -63,7 +63,7 @@
 void RenderSVGGradientStop::layout()
 {
     StackStats::LayoutCheckPoint layoutCheckPoint;
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 SVGGradientElement* RenderSVGGradientStop::gradientElement() const
diff --git a/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp b/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp
index 9fc703e..81116fd 100644
--- a/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp
@@ -33,7 +33,7 @@
     StackStats::LayoutCheckPoint layoutCheckPoint;
     ASSERT(needsLayout());
     SVGRenderSupport::layoutChildren(this, selfNeedsLayout());
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderSVGHiddenContainer::paint(PaintInfo&, const LayoutPoint&)
diff --git a/Source/core/rendering/svg/RenderSVGImage.cpp b/Source/core/rendering/svg/RenderSVGImage.cpp
index 3717f9d..9456092 100644
--- a/Source/core/rendering/svg/RenderSVGImage.cpp
+++ b/Source/core/rendering/svg/RenderSVGImage.cpp
@@ -68,7 +68,7 @@
     // by setting the image's container size to its intrinsic size.
     // See: http://www.w3.org/TR/SVG/single-page.html, 7.8 The ‘preserveAspectRatio’ attribute.
     if (image->preserveAspectRatioCurrentValue().align() == SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE) {
-        if (CachedImage* cachedImage = m_imageResource->cachedImage()) {
+        if (ImageResource* cachedImage = m_imageResource->cachedImage()) {
             LayoutSize intrinsicSize = cachedImage->imageSizeForRenderer(0, style()->effectiveZoom());
             if (intrinsicSize != m_imageResource->imageSize(style()->effectiveZoom())) {
                 m_imageResource->setContainerSizeForRenderer(roundedIntSize(intrinsicSize));
@@ -117,7 +117,7 @@
         RenderSVGModelObject::setNeedsBoundariesUpdate();
 
     repainter.repaintAfterLayout();
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint&)
diff --git a/Source/core/rendering/svg/RenderSVGResource.cpp b/Source/core/rendering/svg/RenderSVGResource.cpp
index 9ecdfdf..6a2d951 100644
--- a/Source/core/rendering/svg/RenderSVGResource.cpp
+++ b/Source/core/rendering/svg/RenderSVGResource.cpp
@@ -191,7 +191,7 @@
     ASSERT(object->node());
 
     if (needsLayout)
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 
     removeFromCacheAndInvalidateDependencies(object, needsLayout);
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
index 33fb263..9d78c84 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
@@ -191,7 +191,7 @@
         if (!renderer)
             continue;
         SVGResourcesCache::clientStyleChanged(renderer, StyleDifferenceLayout, renderer->style());
-        renderer->setNeedsLayout(true);
+        renderer->setNeedsLayout();
     }
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGRoot.cpp b/Source/core/rendering/svg/RenderSVGRoot.cpp
index 7f52741..3e63935 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.cpp
+++ b/Source/core/rendering/svg/RenderSVGRoot.cpp
@@ -251,7 +251,7 @@
 
     repainter.repaintAfterLayout();
 
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
diff --git a/Source/core/rendering/svg/RenderSVGShape.cpp b/Source/core/rendering/svg/RenderSVGShape.cpp
index 08b862e..522f7ab 100644
--- a/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -168,7 +168,7 @@
         RenderSVGModelObject::setNeedsBoundariesUpdate();
 
     repainter.repaintAfterLayout();
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 Path* RenderSVGShape::nonScalingStrokePath(const Path* path, const AffineTransform& strokeTransform) const
diff --git a/Source/core/rendering/svg/RenderSVGText.cpp b/Source/core/rendering/svg/RenderSVGText.cpp
index f3e17a0..bbcbf95 100644
--- a/Source/core/rendering/svg/RenderSVGText.cpp
+++ b/Source/core/rendering/svg/RenderSVGText.cpp
@@ -428,7 +428,7 @@
         RenderSVGBlock::setNeedsBoundariesUpdate();
 
     repainter.repaintAfterLayout();
-    setNeedsLayout(false);
+    clearNeedsLayout();
 }
 
 RootInlineBox* RenderSVGText::createRootInlineBox()
diff --git a/Source/core/rendering/svg/SVGRenderSupport.cpp b/Source/core/rendering/svg/SVGRenderSupport.cpp
index 8d4a272..09fdae4 100644
--- a/Source/core/rendering/svg/SVGRenderSupport.cpp
+++ b/Source/core/rendering/svg/SVGRenderSupport.cpp
@@ -241,7 +241,7 @@
         }
 
         if (needsLayout)
-            child->setNeedsLayout(true, MarkOnlyThis);
+            child->setNeedsLayout(MarkOnlyThis);
 
         if (child->needsLayout()) {
             child->layout();
diff --git a/Source/core/scripts/make_style_builder.py b/Source/core/scripts/make_style_builder.py
index e6cf16b..b408c94 100755
--- a/Source/core/scripts/make_style_builder.py
+++ b/Source/core/scripts/make_style_builder.py
@@ -38,11 +38,7 @@
     class_name = 'StyleBuilder'
 
     valid_values = {
-        'apply_type': ['default', 'length'],
         'svg': [True, False],
-        'use_none': [True, False],
-        'use_intrinsic': [True, False],
-        'use_auto': [True, False],
         'custom_all': [True, False],
         'custom_initial': [True, False],
         'custom_inherit': [True, False],
@@ -50,10 +46,10 @@
     }
     defaults = {
         'condition': None,
-        'apply_type': 'default',
         'name_for_methods': None,
         'use_handlers_for': None,
         'svg': False,
+        'converter': None,
 # These depend on property name by default
         'type_name': None,
         'getter': None,
@@ -65,10 +61,6 @@
         'custom_initial': False,
         'custom_inherit': False,
         'custom_value': False,
-# For the length apply type. Will get moved out to StyleBuilderFunctions.cpp.tmpl
-        'use_none': False,
-        'use_intrinsic': False,
-        'use_auto': False,
     }
 
     def __init__(self, in_files, enabled_conditions):
diff --git a/Source/core/scripts/make_style_shorthands.py b/Source/core/scripts/make_style_shorthands.py
index db5d188..c73de2f 100644
--- a/Source/core/scripts/make_style_shorthands.py
+++ b/Source/core/scripts/make_style_shorthands.py
@@ -40,6 +40,7 @@
 
     defaults = {
         'longhands': "",
+        'runtimeEnabledShorthand': None,
     }
 
     def __init__(self, in_files, enabled_conditions):
@@ -61,6 +62,9 @@
                 longhand = self._create_css_property_name_enum_value(longhand)
                 property["camel_case_longhands"].append(longhand)
                 self._longhand_dictionary[longhand].append(property)
+            if property["runtimeEnabledShorthand"] is not None:
+                lowerFirstConditional = self._lower_first(property["runtimeEnabledShorthand"])
+                property["runtime_conditional_getter"] = "%sEnabled" % lowerFirstConditional
         self._properties = dict((property["property_id"], property) for property in self._properties)
 
 # FIXME: some of these might be better in a utils file
@@ -70,6 +74,11 @@
     def _create_css_property_name_enum_value(self, property_name):
         return "CSSProperty" + property_name
 
+    def _lower_first(self, string):
+        lowered = string[0].lower() + string[1:]
+        lowered = lowered.replace("cSS", "css")
+        return lowered
+
     @template_expander.use_jinja("StylePropertyShorthand.cpp.tmpl")
     def generate_style_property_shorthand_cpp(self):
         return {
diff --git a/Source/core/scripts/templates/StyleBuilder.cpp.tmpl b/Source/core/scripts/templates/StyleBuilder.cpp.tmpl
index 0d25729..a13f2b5 100644
--- a/Source/core/scripts/templates/StyleBuilder.cpp.tmpl
+++ b/Source/core/scripts/templates/StyleBuilder.cpp.tmpl
@@ -21,56 +21,6 @@
 
 namespace WebCore {
 
-{%- macro apply_value_length(property) -%}
-    if (!value->isPrimitiveValue())
-        return;
-
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-    Length length;
-    switch(primitiveValue->getValueID()) {
-
-{%- if property.use_none %}
-    case CSSValueNone:
-        length = Length(Undefined);
-        break;
-{%- endif %}
-
-{%- if property.use_intrinsic %}
-    case CSSValueIntrinsic:
-        length = Length(Intrinsic);
-        break;
-    case CSSValueMinIntrinsic:
-        length = Length(MinIntrinsic);
-        break;
-    case CSSValueWebkitMinContent:
-        length = Length(MinContent);
-        break;
-    case CSSValueWebkitMaxContent:
-        length = Length(MaxContent);
-        break;
-    case CSSValueWebkitFillAvailable:
-        length = Length(FillAvailable);
-        break;
-    case CSSValueWebkitFitContent:
-        length = Length(FitContent);
-        break;
-{%- endif %}
-
-{%- if property.use_auto %}
-    case CSSValueAuto:
-        break; // default ctor is auto
-{%- endif %}
-
-    case CSSValueInvalid:
-        length = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
-        length.setQuirk(primitiveValue->isQuirkValue());
-        break;
-    default:
-        ASSERT_NOT_REACHED();
-    }
-    {{ set_value(property) }}(length);
-{%- endmacro %}
-
 {%- for property_id, property in properties.items() if not property.use_handlers_for %}
 {%- call wrap_with_condition(property.condition) %}
 {%- set apply_type = property.apply_type %}
@@ -100,8 +50,8 @@
 {%- if not property.custom_value %}
 void StyleBuilderFunctions::applyValue{{property_id}}(StyleResolverState& state, CSSValue* value)
 {
-{%- if apply_type == "length" %}
-    {{ apply_value_length(property) }}
+{%- if property.converter %}
+    {{ set_value(property) }}(StyleBuilderConverter::{{property.converter}}(state, value));
 {%- else %}
     {{ set_value(property) }}(static_cast<{{property.type_name}}>(*toCSSPrimitiveValue(value)));
 {%- endif %}
diff --git a/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl b/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
index 861e733..f9a486a 100644
--- a/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
+++ b/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
@@ -243,39 +243,6 @@
 {{ apply_value_border_image_source("CSSPropertyBorderImageSource") }}
 {{ apply_value_border_image_source("CSSPropertyWebkitMaskBoxImageSource") }}
 
-{%- macro apply_value_border_radius(property_id) %}
-{{ declare_value_function(property_id) }}
-{
-    {%- set property = properties[property_id] %}
-    if (!value->isPrimitiveValue())
-        return;
-
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-    Pair* pair = primitiveValue->getPairValue();
-    if (!pair || !pair->first() || !pair->second())
-        return;
-
-    Length radiusWidth = pair->first()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
-    Length radiusHeight = pair->second()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
-    int width = radiusWidth.value();
-    int height = radiusHeight.value();
-    if (width < 0 || height < 0)
-        return;
-    if (!width)
-        radiusHeight = radiusWidth; // Null out the other value.
-    else if (!height)
-        radiusWidth = radiusHeight; // Null out the other value.
-
-    LengthSize size(radiusWidth, radiusHeight);
-    {{ set_value(property) }}(size);
-}
-{%- endmacro %}
-
-{{ apply_value_border_radius("CSSPropertyBorderBottomLeftRadius") }}
-{{ apply_value_border_radius("CSSPropertyBorderBottomRightRadius") }}
-{{ apply_value_border_radius("CSSPropertyBorderTopLeftRadius") }}
-{{ apply_value_border_radius("CSSPropertyBorderTopRightRadius") }}
-
 {%- macro apply_color(property_id, default_getter="color", initial_color=none, inherit_color=false) %}
 {%- set property = properties[property_id] %}
 {%- set visited_link_setter = "setVisitedLink" + property.camel_case_name %}
@@ -334,24 +301,6 @@
 {{ apply_color("CSSPropertyWebkitTextFillColor") }}
 {{ apply_color("CSSPropertyWebkitTextStrokeColor") }}
 
-{%- macro apply_value_compute_length(property_id) %}
-{{ declare_value_function(property_id) }}
-{
-    {%- set property = properties[property_id] %}
-    if (!value->isPrimitiveValue())
-        return;
-
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-    float zoom = state.style()->effectiveZoom();
-    {{ set_value(property) }}(primitiveValue->computeLength<{{property.type_name}}>(state.style(), state.rootElementStyle(), zoom));
-}
-{%- endmacro %}
-
-{{ apply_value_compute_length("CSSPropertyOutlineOffset") }}
-{{ apply_value_compute_length("CSSPropertyWebkitBorderHorizontalSpacing") }}
-{{ apply_value_compute_length("CSSPropertyWebkitBorderVerticalSpacing") }}
-{{ apply_value_compute_length("CSSPropertyWebkitTransformOriginZ") }}
-
 {%- macro apply_counter(property_id, action) %}
 {%- set property = properties[property_id] %}
 {{ declare_initial_function(property_id) }} { }
@@ -525,48 +474,6 @@
 {{ apply_font("CSSPropertyWebkitFontKerning", "Kerning", "FontDescription::AutoKerning", "FontDescription::Kerning") }}
 {{ apply_font("CSSPropertyWebkitFontSmoothing", "FontSmoothing", "AutoSmoothing", "FontSmoothingMode") }}
 
-{%- macro apply_value_line_width(property_id) %}
-{{ declare_value_function(property_id) }}
-{
-    {%- set property = properties[property_id] %}
-    {%- set T = property.type_name %}
-    if (!value->isPrimitiveValue())
-        return;
-
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-    CSSValueID valueID = primitiveValue->getValueID();
-    {{ T }} length;
-    if (valueID == CSSValueThin) {
-        length = 1;
-    } else if (valueID == CSSValueMedium) {
-        length = 3;
-    } else if (valueID == CSSValueThick) {
-        length = 5;
-    } else if (valueID == CSSValueInvalid) {
-        float zoom = state.style()->effectiveZoom();
-        // Any original result that was >= 1 should not be allowed to fall below 1.
-        // This keeps border lines from vanishing.
-        length = primitiveValue->computeLength<{{T}}>(state.style(), state.rootElementStyle(), zoom);
-        if (zoom < 1.0f && length < 1.0) {
-            {{ T }} originalLength = primitiveValue->computeLength<{{T}}>(state.style(), state.rootElementStyle(), 1.0);
-            if (originalLength >= 1.0)
-                length = 1.0;
-        }
-    } else {
-        ASSERT_NOT_REACHED();
-        length = 0;
-    }
-    {{ set_value(property) }}(length);
-}
-{%- endmacro %}
-
-{{ apply_value_line_width("CSSPropertyBorderBottomWidth") }}
-{{ apply_value_line_width("CSSPropertyBorderLeftWidth") }}
-{{ apply_value_line_width("CSSPropertyBorderRightWidth") }}
-{{ apply_value_line_width("CSSPropertyBorderTopWidth") }}
-{{ apply_value_line_width("CSSPropertyOutlineWidth") }}
-{{ apply_value_line_width("CSSPropertyWebkitColumnRuleWidth") }}
-
 {%- macro apply_value_number(property_id, id_for_minus_one) %}
 {{ declare_value_function(property_id) }}
 {
@@ -606,47 +513,4 @@
 {{ apply_value_shape("CSSPropertyWebkitShapeInside") }}
 {{ apply_value_shape("CSSPropertyWebkitShapeOutside") }}
 
-{%- macro apply_value_spacing(property_id) %}
-{{ declare_value_function(property_id) }}
-{
-    {%- set property = properties[property_id] %}
-    {%- set T = property.type_name %}
-    if (!value->isPrimitiveValue())
-        return;
-
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-    {{ T }} length;
-    if (primitiveValue->getValueID() == CSSValueNormal) {
-        length = 0;
-    } else {
-        float zoom = state.useSVGZoomRules() ? 1.0f : state.style()->effectiveZoom();
-        length = primitiveValue->computeLength<{{T}}>(state.style(), state.rootElementStyle(), zoom);
-    }
-    {{ set_value(property) }}(length);
-}
-{%- endmacro %}
-
-{{ apply_value_spacing("CSSPropertyLetterSpacing") }}
-{{ apply_value_spacing("CSSPropertyWordSpacing") }}
-
-{%- macro apply_value_string(property_id, id_for_none) %}
-{{ declare_value_function(property_id) }}
-{
-    {%- set property = properties[property_id] %}
-    if (!value->isPrimitiveValue())
-        return;
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-    if (primitiveValue->getValueID() == {{id_for_none}})
-        {{ set_value(property) }}(nullAtom);
-    else
-        {{ set_value(property) }}(primitiveValue->getStringValue());
-}
-{%- endmacro %}
-
-{{ apply_value_string("CSSPropertyWebkitHighlight", "CSSValueNone") }}
-{{ apply_value_string("CSSPropertyWebkitHyphenateCharacter", "CSSValueAuto") }}
-{{ apply_value_string("CSSPropertyWebkitLineGrid", "CSSValueNone") }}
-{{ apply_value_string("CSSPropertyWebkitFlowFrom", "CSSValueNone") }}
-{{ apply_value_string("CSSPropertyWebkitFlowInto", "CSSValueNone") }}
-
 } // namespace WebCore
diff --git a/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl b/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl
index f3e1109..a7063e2 100644
--- a/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl
+++ b/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl
@@ -1,6 +1,11 @@
 {% from "macros.tmpl" import wrap_with_condition, license -%}
 {{ license() }}
 
+#ifndef StyleBuilderFunctions_h
+#define StyleBuilderFunctions_h
+
+#include "core/css/resolver/StyleBuilderCustom.h"
+
 namespace WebCore {
 
 class CSSValue;
@@ -20,3 +25,5 @@
 };
 
 } // namespace WebCore
+
+#endif
diff --git a/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl b/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl
index 8c8c16a..a491e03 100644
--- a/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl
+++ b/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl
@@ -21,6 +21,7 @@
 
 #include "config.h"
 #include "StylePropertyShorthand.h"
+#include "RuntimeEnabledFeatures.h"
 
 #include "wtf/HashMap.h"
 #include "wtf/StdLibExtras.h"
@@ -44,15 +45,19 @@
 // Returns an empty list if the property is not a shorthand
 const StylePropertyShorthand& shorthandForProperty(CSSPropertyID propertyID)
 {
+    DEFINE_STATIC_LOCAL(StylePropertyShorthand, emptyShorthand, ());
     switch (propertyID) {
 {%- for property_id, property in properties.items() %}
     {%- if property.camel_case_name not in ["width", "height", "marker"] %}
         case {{ property_id }}:
+        {%- if property.runtime_conditional_getter %}
+            if (!RuntimeEnabledFeatures::{{ property.runtime_conditional_getter }}())
+                return emptyShorthand;
+        {%- endif %}
             return {{ property.camel_case_name }}Shorthand();
     {%- endif %}
 {%- endfor %}
     default: {
-        DEFINE_STATIC_LOCAL(StylePropertyShorthand, emptyShorthand, ());
         return emptyShorthand;
     }
     }
diff --git a/Source/core/svg/SVGAngle.cpp b/Source/core/svg/SVGAngle.cpp
index 661f935..e88d5da 100644
--- a/Source/core/svg/SVGAngle.cpp
+++ b/Source/core/svg/SVGAngle.cpp
@@ -114,15 +114,15 @@
 {
     switch (m_unitType) {
     case SVG_ANGLETYPE_DEG: {
-        DEFINE_STATIC_LOCAL(String, degString, (ASCIILiteral("deg")));
+        DEFINE_STATIC_LOCAL(String, degString, ("deg"));
         return String::number(m_valueInSpecifiedUnits) + degString;
     }
     case SVG_ANGLETYPE_RAD: {
-        DEFINE_STATIC_LOCAL(String, radString, (ASCIILiteral("rad")));
+        DEFINE_STATIC_LOCAL(String, radString, ("rad"));
         return String::number(m_valueInSpecifiedUnits) + radString;
     }
     case SVG_ANGLETYPE_GRAD: {
-        DEFINE_STATIC_LOCAL(String, gradString, (ASCIILiteral("grad")));
+        DEFINE_STATIC_LOCAL(String, gradString, ("grad"));
         return String::number(m_valueInSpecifiedUnits) + gradString;
     }
     case SVG_ANGLETYPE_UNSPECIFIED:
diff --git a/Source/core/svg/SVGClipPathElement.cpp b/Source/core/svg/SVGClipPathElement.cpp
index efea4ee..fffc54d 100644
--- a/Source/core/svg/SVGClipPathElement.cpp
+++ b/Source/core/svg/SVGClipPathElement.cpp
@@ -93,7 +93,7 @@
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 void SVGClipPathElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -104,7 +104,7 @@
         return;
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 RenderObject* SVGClipPathElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGDocument.cpp b/Source/core/svg/SVGDocument.cpp
index ddab3c4..0823df0 100644
--- a/Source/core/svg/SVGDocument.cpp
+++ b/Source/core/svg/SVGDocument.cpp
@@ -94,6 +94,11 @@
     }
 }
 
+PassRefPtr<Document> SVGDocument::cloneDocumentWithoutChildren()
+{
+    return create();
+}
+
 bool SVGDocument::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
 {
     if (childContext.node()->hasTagName(SVGNames::svgTag))
diff --git a/Source/core/svg/SVGDocument.h b/Source/core/svg/SVGDocument.h
index 273db02..163188b 100644
--- a/Source/core/svg/SVGDocument.h
+++ b/Source/core/svg/SVGDocument.h
@@ -47,6 +47,8 @@
     void startPan(const FloatPoint& start);
     void updatePan(const FloatPoint& pos) const;
 
+    virtual PassRefPtr<Document> cloneDocumentWithoutChildren() OVERRIDE FINAL;
+
 private:
     SVGDocument(const DocumentInit&);
 
diff --git a/Source/core/svg/SVGElementInstance.idl b/Source/core/svg/SVGElementInstance.idl
index 3fbf3b7..4344913 100644
--- a/Source/core/svg/SVGElementInstance.idl
+++ b/Source/core/svg/SVGElementInstance.idl
@@ -36,46 +36,46 @@
     readonly attribute SVGElementInstance nextSibling;
 
     // EventTarget
-    [NotEnumerable] attribute EventListener onabort;
-    [NotEnumerable] attribute EventListener onblur;
-    [NotEnumerable] attribute EventListener onchange;
-    [NotEnumerable] attribute EventListener onclick;
-    [NotEnumerable] attribute EventListener oncontextmenu;
-    [NotEnumerable] attribute EventListener ondblclick;
-    [NotEnumerable] attribute EventListener onerror;
-    [NotEnumerable] attribute EventListener onfocus;
-    [NotEnumerable] attribute EventListener oninput;
-    [NotEnumerable] attribute EventListener onkeydown;
-    [NotEnumerable] attribute EventListener onkeypress;
-    [NotEnumerable] attribute EventListener onkeyup;
-    [NotEnumerable] attribute EventListener onload;
-    [NotEnumerable] attribute EventListener onmousedown;
-    [NotEnumerable] attribute EventListener onmouseenter;
-    [NotEnumerable] attribute EventListener onmouseleave;
-    [NotEnumerable] attribute EventListener onmousemove;
-    [NotEnumerable] attribute EventListener onmouseout;
-    [NotEnumerable] attribute EventListener onmouseover;
-    [NotEnumerable] attribute EventListener onmouseup;
-    [NotEnumerable] attribute EventListener onmousewheel;
-    [NotEnumerable] attribute EventListener onbeforecut;
-    [NotEnumerable] attribute EventListener oncut;
-    [NotEnumerable] attribute EventListener onbeforecopy;
-    [NotEnumerable] attribute EventListener oncopy;
-    [NotEnumerable] attribute EventListener onbeforepaste;
-    [NotEnumerable] attribute EventListener onpaste;
-    [NotEnumerable] attribute EventListener ondragenter;
-    [NotEnumerable] attribute EventListener ondragover;
-    [NotEnumerable] attribute EventListener ondragleave;
-    [NotEnumerable] attribute EventListener ondrop;
-    [NotEnumerable] attribute EventListener ondragstart;
-    [NotEnumerable] attribute EventListener ondrag;
-    [NotEnumerable] attribute EventListener ondragend;
-    [NotEnumerable] attribute EventListener onreset;
-    [NotEnumerable] attribute EventListener onresize;
-    [NotEnumerable] attribute EventListener onscroll;
-    [NotEnumerable] attribute EventListener onsearch;
-    [NotEnumerable] attribute EventListener onselect;
-    [NotEnumerable] attribute EventListener onselectstart;
-    [NotEnumerable] attribute EventListener onsubmit;
-    [NotEnumerable] attribute EventListener onunload;
+    [NotEnumerable] attribute EventHandler onabort;
+    [NotEnumerable] attribute EventHandler onblur;
+    [NotEnumerable] attribute EventHandler onchange;
+    [NotEnumerable] attribute EventHandler onclick;
+    [NotEnumerable] attribute EventHandler oncontextmenu;
+    [NotEnumerable] attribute EventHandler ondblclick;
+    [NotEnumerable] attribute EventHandler onerror;
+    [NotEnumerable] attribute EventHandler onfocus;
+    [NotEnumerable] attribute EventHandler oninput;
+    [NotEnumerable] attribute EventHandler onkeydown;
+    [NotEnumerable] attribute EventHandler onkeypress;
+    [NotEnumerable] attribute EventHandler onkeyup;
+    [NotEnumerable] attribute EventHandler onload;
+    [NotEnumerable] attribute EventHandler onmousedown;
+    [NotEnumerable] attribute EventHandler onmouseenter;
+    [NotEnumerable] attribute EventHandler onmouseleave;
+    [NotEnumerable] attribute EventHandler onmousemove;
+    [NotEnumerable] attribute EventHandler onmouseout;
+    [NotEnumerable] attribute EventHandler onmouseover;
+    [NotEnumerable] attribute EventHandler onmouseup;
+    [NotEnumerable] attribute EventHandler onmousewheel;
+    [NotEnumerable] attribute EventHandler onbeforecut;
+    [NotEnumerable] attribute EventHandler oncut;
+    [NotEnumerable] attribute EventHandler onbeforecopy;
+    [NotEnumerable] attribute EventHandler oncopy;
+    [NotEnumerable] attribute EventHandler onbeforepaste;
+    [NotEnumerable] attribute EventHandler onpaste;
+    [NotEnumerable] attribute EventHandler ondragenter;
+    [NotEnumerable] attribute EventHandler ondragover;
+    [NotEnumerable] attribute EventHandler ondragleave;
+    [NotEnumerable] attribute EventHandler ondrop;
+    [NotEnumerable] attribute EventHandler ondragstart;
+    [NotEnumerable] attribute EventHandler ondrag;
+    [NotEnumerable] attribute EventHandler ondragend;
+    [NotEnumerable] attribute EventHandler onreset;
+    [NotEnumerable] attribute EventHandler onresize;
+    [NotEnumerable] attribute EventHandler onscroll;
+    [NotEnumerable] attribute EventHandler onsearch;
+    [NotEnumerable] attribute EventHandler onselect;
+    [NotEnumerable] attribute EventHandler onselectstart;
+    [NotEnumerable] attribute EventHandler onsubmit;
+    [NotEnumerable] attribute EventHandler onunload;
 };
diff --git a/Source/core/svg/SVGFEImageElement.cpp b/Source/core/svg/SVGFEImageElement.cpp
index 263ed57..b67789c 100644
--- a/Source/core/svg/SVGFEImageElement.cpp
+++ b/Source/core/svg/SVGFEImageElement.cpp
@@ -26,8 +26,8 @@
 #include "SVGNames.h"
 #include "XLinkNames.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedImage.h"
 #include "core/loader/cache/FetchRequest.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/platform/graphics/Image.h"
 #include "core/rendering/svg/RenderSVGResource.h"
diff --git a/Source/core/svg/SVGFEImageElement.h b/Source/core/svg/SVGFEImageElement.h
index d82146a..64f326d 100644
--- a/Source/core/svg/SVGFEImageElement.h
+++ b/Source/core/svg/SVGFEImageElement.h
@@ -21,7 +21,7 @@
 #ifndef SVGFEImageElement_h
 #define SVGFEImageElement_h
 
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/svg/SVGAnimatedBoolean.h"
@@ -36,7 +36,7 @@
 class SVGFEImageElement FINAL : public SVGFilterPrimitiveStandardAttributes,
                                 public SVGURIReference,
                                 public SVGExternalResourcesRequired,
-                                public CachedImageClient {
+                                public ImageResourceClient {
 public:
     static PassRefPtr<SVGFEImageElement> create(const QualifiedName&, Document*);
 
@@ -66,7 +66,7 @@
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    ResourcePtr<CachedImage> m_cachedImage;
+    ResourcePtr<ImageResource> m_cachedImage;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFilterElement.cpp b/Source/core/svg/SVGFilterElement.cpp
index c7e9be0..4de38a6 100644
--- a/Source/core/svg/SVGFilterElement.cpp
+++ b/Source/core/svg/SVGFilterElement.cpp
@@ -98,7 +98,7 @@
     setFilterResYBaseValue(filterResY);
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 bool SVGFilterElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -170,7 +170,7 @@
         updateRelativeLengthsInformation();
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 void SVGFilterElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -181,7 +181,7 @@
         return;
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 RenderObject* SVGFilterElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGFontFaceElement.cpp b/Source/core/svg/SVGFontFaceElement.cpp
index 40c4168..eca1641 100644
--- a/Source/core/svg/SVGFontFaceElement.cpp
+++ b/Source/core/svg/SVGFontFaceElement.cpp
@@ -307,7 +307,7 @@
     if (describesParentFont) {
         // Traverse parsed CSS values and associate CSSFontFaceSrcValue elements with ourselves.
         RefPtr<CSSValue> src = m_fontFaceRule->properties()->getPropertyCSSValue(CSSPropertySrc);
-        CSSValueList* srcList = static_cast<CSSValueList*>(src.get());
+        CSSValueList* srcList = toCSSValueList(src.get());
 
         unsigned srcLength = srcList ? srcList->length() : 0;
         for (unsigned i = 0; i < srcLength; i++) {
diff --git a/Source/core/svg/SVGFontFaceUriElement.cpp b/Source/core/svg/SVGFontFaceUriElement.cpp
index eb726eb..569ca30 100644
--- a/Source/core/svg/SVGFontFaceUriElement.cpp
+++ b/Source/core/svg/SVGFontFaceUriElement.cpp
@@ -27,8 +27,8 @@
 #include "XLinkNames.h"
 #include "core/css/CSSFontFaceSrcValue.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedFont.h"
 #include "core/loader/cache/FetchRequest.h"
+#include "core/loader/cache/FontResource.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/svg/SVGFontFaceElement.h"
 
@@ -50,8 +50,8 @@
 
 SVGFontFaceUriElement::~SVGFontFaceUriElement()
 {
-    if (m_cachedFont)
-        m_cachedFont->removeClient(this);
+    if (m_resource)
+        m_resource->removeClient(this);
 }
 
 PassRefPtr<CSSFontFaceSrcValue> SVGFontFaceUriElement::srcValue() const
@@ -90,20 +90,21 @@
 
 void SVGFontFaceUriElement::loadFont()
 {
-    if (m_cachedFont)
-        m_cachedFont->removeClient(this);
+    if (m_resource)
+        m_resource->removeClient(this);
 
     const AtomicString& href = getAttribute(XLinkNames::hrefAttr);
     if (!href.isNull()) {
         ResourceFetcher* fetcher = document()->fetcher();
         FetchRequest request(ResourceRequest(document()->completeURL(href)), localName());
-        m_cachedFont = fetcher->requestFont(request);
-        if (m_cachedFont) {
-            m_cachedFont->addClient(this);
-            m_cachedFont->beginLoadIfNeeded(fetcher);
+        m_resource = fetcher->requestFont(request);
+        if (m_resource) {
+            m_resource->addClient(this);
+            m_resource->beginLoadIfNeeded(fetcher);
         }
-    } else
-        m_cachedFont = 0;
+    } else {
+        m_resource = 0;
+    }
 }
 
 }
diff --git a/Source/core/svg/SVGFontFaceUriElement.h b/Source/core/svg/SVGFontFaceUriElement.h
index 1d06358..99d1046 100644
--- a/Source/core/svg/SVGFontFaceUriElement.h
+++ b/Source/core/svg/SVGFontFaceUriElement.h
@@ -21,7 +21,7 @@
 #define SVGFontFaceUriElement_h
 
 #if ENABLE(SVG_FONTS)
-#include "core/loader/cache/CachedFont.h"
+#include "core/loader/cache/FontResource.h"
 #include "core/loader/cache/ResourcePtr.h"
 #include "core/svg/SVGElement.h"
 
@@ -29,7 +29,7 @@
 
 class CSSFontFaceSrcValue;
 
-class SVGFontFaceUriElement FINAL : public SVGElement, public CachedFontClient {
+class SVGFontFaceUriElement FINAL : public SVGElement, public FontResourceClient {
 public:
     static PassRefPtr<SVGFontFaceUriElement> create(const QualifiedName&, Document*);
 
@@ -48,7 +48,7 @@
 
     void loadFont();
 
-    ResourcePtr<CachedFont> m_cachedFont;
+    ResourcePtr<FontResource> m_resource;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGGradientElement.cpp b/Source/core/svg/SVGGradientElement.cpp
index 5788147..17d6658 100644
--- a/Source/core/svg/SVGGradientElement.cpp
+++ b/Source/core/svg/SVGGradientElement.cpp
@@ -122,7 +122,7 @@
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 void SVGGradientElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -133,7 +133,7 @@
         return;
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 Vector<Gradient::ColorStop> SVGGradientElement::buildStops()
diff --git a/Source/core/svg/SVGImageElement.cpp b/Source/core/svg/SVGImageElement.cpp
index c90901a..33cca0b 100644
--- a/Source/core/svg/SVGImageElement.cpp
+++ b/Source/core/svg/SVGImageElement.cpp
@@ -199,7 +199,7 @@
         if (imageObj->imageResource()->hasImage())
             return;
 
-        imageObj->imageResource()->setCachedImage(m_imageLoader.image());
+        imageObj->imageResource()->setImageResource(m_imageLoader.image());
     }
 }
 
diff --git a/Source/core/svg/SVGImageLoader.cpp b/Source/core/svg/SVGImageLoader.cpp
index 1cbd94f..75dd0d4 100644
--- a/Source/core/svg/SVGImageLoader.cpp
+++ b/Source/core/svg/SVGImageLoader.cpp
@@ -25,7 +25,7 @@
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/svg/SVGImageElement.h"
 
 namespace WebCore {
diff --git a/Source/core/svg/SVGLinearGradientElement.cpp b/Source/core/svg/SVGLinearGradientElement.cpp
index cb55892..583fcf4 100644
--- a/Source/core/svg/SVGLinearGradientElement.cpp
+++ b/Source/core/svg/SVGLinearGradientElement.cpp
@@ -110,7 +110,7 @@
     updateRelativeLengthsInformation();
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 RenderObject* SVGLinearGradientElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGMarkerElement.cpp b/Source/core/svg/SVGMarkerElement.cpp
index 4d010c0..f872911 100644
--- a/Source/core/svg/SVGMarkerElement.cpp
+++ b/Source/core/svg/SVGMarkerElement.cpp
@@ -172,7 +172,7 @@
         updateRelativeLengthsInformation();
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 void SVGMarkerElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -183,7 +183,7 @@
         return;
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 void SVGMarkerElement::setOrientToAuto()
diff --git a/Source/core/svg/SVGMaskElement.cpp b/Source/core/svg/SVGMaskElement.cpp
index 5fe2d9c..2726fc1 100644
--- a/Source/core/svg/SVGMaskElement.cpp
+++ b/Source/core/svg/SVGMaskElement.cpp
@@ -138,7 +138,7 @@
         updateRelativeLengthsInformation();
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 void SVGMaskElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -149,7 +149,7 @@
         return;
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 RenderObject* SVGMaskElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGPatternElement.cpp b/Source/core/svg/SVGPatternElement.cpp
index 9502020..aeedfb4 100644
--- a/Source/core/svg/SVGPatternElement.cpp
+++ b/Source/core/svg/SVGPatternElement.cpp
@@ -156,7 +156,7 @@
         updateRelativeLengthsInformation();
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 void SVGPatternElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -167,7 +167,7 @@
         return;
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 RenderObject* SVGPatternElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGRadialGradientElement.cpp b/Source/core/svg/SVGRadialGradientElement.cpp
index 1a2bfb8..6ba70e5 100644
--- a/Source/core/svg/SVGRadialGradientElement.cpp
+++ b/Source/core/svg/SVGRadialGradientElement.cpp
@@ -121,7 +121,7 @@
     updateRelativeLengthsInformation();
 
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 }
 
 RenderObject* SVGRadialGradientElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGSVGElement.cpp b/Source/core/svg/SVGSVGElement.cpp
index ffaaef5..d695883 100644
--- a/Source/core/svg/SVGSVGElement.cpp
+++ b/Source/core/svg/SVGSVGElement.cpp
@@ -215,7 +215,7 @@
 void SVGSVGElement::updateCurrentTranslate()
 {
     if (RenderObject* object = renderer())
-        object->setNeedsLayout(true);
+        object->setNeedsLayout();
 
     if (parentNode() == document() && document()->renderer())
         document()->renderer()->repaint();
diff --git a/Source/core/svg/SVGTransform.cpp b/Source/core/svg/SVGTransform.cpp
index 18324a8..2c44d36 100644
--- a/Source/core/svg/SVGTransform.cpp
+++ b/Source/core/svg/SVGTransform.cpp
@@ -133,27 +133,27 @@
     case SVG_TRANSFORM_UNKNOWN:
         return emptyString();
     case SVG_TRANSFORM_MATRIX: {
-        DEFINE_STATIC_LOCAL(String, matrixString, (ASCIILiteral("matrix(")));
+        DEFINE_STATIC_LOCAL(String, matrixString, ("matrix("));
         return matrixString;
     }
     case SVG_TRANSFORM_TRANSLATE: {
-        DEFINE_STATIC_LOCAL(String, translateString, (ASCIILiteral("translate(")));
+        DEFINE_STATIC_LOCAL(String, translateString, ("translate("));
         return translateString;
     }
     case SVG_TRANSFORM_SCALE: {
-        DEFINE_STATIC_LOCAL(String, scaleString, (ASCIILiteral("scale(")));
+        DEFINE_STATIC_LOCAL(String, scaleString, ("scale("));
         return scaleString;
     }
     case SVG_TRANSFORM_ROTATE: {
-        DEFINE_STATIC_LOCAL(String, rotateString, (ASCIILiteral("rotate(")));
+        DEFINE_STATIC_LOCAL(String, rotateString, ("rotate("));
         return rotateString;
     }
     case SVG_TRANSFORM_SKEWX: {
-        DEFINE_STATIC_LOCAL(String, skewXString, (ASCIILiteral("skewX(")));
+        DEFINE_STATIC_LOCAL(String, skewXString, ("skewX("));
         return skewXString;
     }
     case SVG_TRANSFORM_SKEWY: {
-        DEFINE_STATIC_LOCAL(String, skewYString, (ASCIILiteral("skewY(")));
+        DEFINE_STATIC_LOCAL(String, skewYString, ("skewY("));
         return skewYString;
     }
     }
diff --git a/Source/core/svg/SVGUseElement.cpp b/Source/core/svg/SVGUseElement.cpp
index 2656c09..9ea0250 100644
--- a/Source/core/svg/SVGUseElement.cpp
+++ b/Source/core/svg/SVGUseElement.cpp
@@ -34,7 +34,7 @@
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/loader/cache/CachedDocument.h"
+#include "core/loader/cache/DocumentResource.h"
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/ResourceFetcher.h"
 #include "core/rendering/svg/RenderSVGResource.h"
@@ -98,7 +98,7 @@
 
 SVGUseElement::~SVGUseElement()
 {
-    setCachedDocument(0);
+    setDocumentResource(0);
 
     clearResourceReferences();
 }
@@ -196,12 +196,12 @@
 
 Document* SVGUseElement::externalDocument() const
 {
-    if (m_cachedDocument && m_cachedDocument->isLoaded()) {
+    if (m_resource && m_resource->isLoaded()) {
         // Gracefully handle error condition.
-        if (m_cachedDocument->errorOccurred())
+        if (m_resource->errorOccurred())
             return 0;
-        ASSERT(m_cachedDocument->document());
-        return m_cachedDocument->document();
+        ASSERT(m_resource->document());
+        return m_resource->document();
     }
     return 0;
 }
@@ -235,10 +235,11 @@
             KURL url = document()->completeURL(hrefCurrentValue());
             if (url.hasFragmentIdentifier()) {
                 FetchRequest request(ResourceRequest(url.string()), localName());
-                setCachedDocument(document()->fetcher()->requestSVGDocument(request));
+                setDocumentResource(document()->fetcher()->requestSVGDocument(request));
             }
-        } else
-            setCachedDocument(0);
+        } else {
+            setDocumentResource(0);
+        }
 
         if (!m_wasInsertedByParser)
             buildPendingResource();
@@ -271,7 +272,7 @@
     ASSERT(element);
 
     if (element->hasTagName(SVGNames::useTag)) {
-        if (toSVGUseElement(element)->cachedDocumentIsStillLoading())
+        if (toSVGUseElement(element)->resourceIsStillLoading())
             return;
     }
 
@@ -704,7 +705,7 @@
     // to walk it completely and expand all <use> elements.
     if (element->hasTagName(SVGNames::useTag)) {
         SVGUseElement* use = toSVGUseElement(element);
-        ASSERT(!use->cachedDocumentIsStillLoading());
+        ASSERT(!use->resourceIsStillLoading());
 
         Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefCurrentValue(), referencedDocument());
         SVGElement* target = 0;
@@ -947,9 +948,9 @@
         SVGExternalResourcesRequired::dispatchLoadEvent(this);
 }
 
-bool SVGUseElement::cachedDocumentIsStillLoading()
+bool SVGUseElement::resourceIsStillLoading()
 {
-    if (m_cachedDocument && m_cachedDocument->isLoading())
+    if (m_resource && m_resource->isLoading())
         return true;
     return false;
 }
@@ -958,8 +959,8 @@
 {
     for (SVGElementInstance* instance = targetElementInstance->firstChild(); instance; instance = instance->nextSibling()) {
         if (SVGUseElement* use = instance->correspondingUseElement()) {
-             if (use->cachedDocumentIsStillLoading())
-                 return true;
+            if (use->resourceIsStillLoading())
+                return true;
         }
         if (instance->hasChildNodes())
             instanceTreeIsLoading(instance);
@@ -977,17 +978,17 @@
     }
 }
 
-void SVGUseElement::setCachedDocument(ResourcePtr<CachedDocument> cachedDocument)
+void SVGUseElement::setDocumentResource(ResourcePtr<DocumentResource> resource)
 {
-    if (m_cachedDocument == cachedDocument)
+    if (m_resource == resource)
         return;
 
-    if (m_cachedDocument)
-        m_cachedDocument->removeClient(this);
+    if (m_resource)
+        m_resource->removeClient(this);
 
-    m_cachedDocument = cachedDocument;
-    if (m_cachedDocument)
-        m_cachedDocument->addClient(this);
+    m_resource = resource;
+    if (m_resource)
+        m_resource->addClient(this);
 }
 
 }
diff --git a/Source/core/svg/SVGUseElement.h b/Source/core/svg/SVGUseElement.h
index 6bd1fb6..1540588 100644
--- a/Source/core/svg/SVGUseElement.h
+++ b/Source/core/svg/SVGUseElement.h
@@ -22,7 +22,7 @@
 #define SVGUseElement_h
 
 #include "SVGNames.h"
-#include "core/loader/cache/CachedDocument.h"
+#include "core/loader/cache/DocumentResource.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
@@ -31,13 +31,13 @@
 
 namespace WebCore {
 
-class CachedDocument;
+class DocumentResource;
 class SVGElementInstance;
 
 class SVGUseElement FINAL : public SVGGraphicsElement,
                             public SVGExternalResourcesRequired,
                             public SVGURIReference,
-                            public CachedDocumentClient {
+                            public DocumentResourceClient {
 public:
     static PassRefPtr<SVGUseElement> create(const QualifiedName&, Document*, bool wasInsertedByParser);
     virtual ~SVGUseElement();
@@ -104,12 +104,12 @@
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    bool cachedDocumentIsStillLoading();
+    bool resourceIsStillLoading();
     Document* externalDocument() const;
     bool instanceTreeIsLoading(SVGElementInstance*);
     virtual void notifyFinished(Resource*);
     Document* referencedDocument() const;
-    void setCachedDocument(ResourcePtr<CachedDocument>);
+    void setDocumentResource(ResourcePtr<DocumentResource>);
 
     // SVGExternalResourcesRequired
     virtual void setHaveFiredLoadEvent(bool haveFiredLoadEvent) { m_haveFiredLoadEvent = haveFiredLoadEvent; }
@@ -121,7 +121,7 @@
     bool m_haveFiredLoadEvent;
     bool m_needsShadowTreeRecreation;
     RefPtr<SVGElementInstance> m_targetElementInstance;
-    ResourcePtr<CachedDocument> m_cachedDocument;
+    ResourcePtr<DocumentResource> m_resource;
     Timer<SVGElement> m_svgLoadEventTimer;
 };
 
diff --git a/Source/core/svg/graphics/SVGImage.cpp b/Source/core/svg/graphics/SVGImage.cpp
index 3a3fc88..bbcfe3c 100644
--- a/Source/core/svg/graphics/SVGImage.cpp
+++ b/Source/core/svg/graphics/SVGImage.cpp
@@ -159,7 +159,7 @@
 }
 
 void SVGImage::drawPatternForContainer(GraphicsContext* context, const FloatSize containerSize, float zoom, const FloatRect& srcRect,
-    const FloatSize& scale, const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect)
+    const FloatSize& scale, const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, BlendMode blendMode)
 {
     FloatRect zoomedContainerRect = FloatRect(FloatPoint(), containerSize);
     zoomedContainerRect.scale(zoom);
@@ -186,7 +186,7 @@
     FloatRect scaledSrcRect = srcRect;
     scaledSrcRect.scale(imageBufferScale.width(), imageBufferScale.height());
 
-    image->drawPattern(context, scaledSrcRect, scaleWithoutCTM, phase, compositeOp, dstRect);
+    image->drawPattern(context, scaledSrcRect, scaleWithoutCTM, phase, compositeOp, dstRect, blendMode);
 }
 
 void SVGImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
@@ -332,7 +332,7 @@
         pageClients.chromeClient = m_chromeClient.get();
 
         // FIXME: If this SVG ends up loading itself, we might leak the world.
-        // The Cache code does not know about CachedImages holding Frames and
+        // The Cache code does not know about ImageResources holding Frames and
         // won't know to break the cycle.
         // This will become an issue when SVGImage will be able to load other
         // SVGImage objects, but we're safe now, because SVGImage can only be
diff --git a/Source/core/svg/graphics/SVGImage.h b/Source/core/svg/graphics/SVGImage.h
index d4d9af4..186f2b7 100644
--- a/Source/core/svg/graphics/SVGImage.h
+++ b/Source/core/svg/graphics/SVGImage.h
@@ -87,7 +87,7 @@
     virtual void draw(GraphicsContext*, const FloatRect& fromRect, const FloatRect& toRect, CompositeOperator, BlendMode) OVERRIDE;
     void drawForContainer(GraphicsContext*, const FloatSize, float, const FloatRect&, const FloatRect&, CompositeOperator, BlendMode);
     void drawPatternForContainer(GraphicsContext*, const FloatSize, float, const FloatRect&, const FloatSize&, const FloatPoint&,
-        CompositeOperator, const FloatRect&);
+        CompositeOperator, const FloatRect&, BlendMode);
 
     OwnPtr<SVGImageChromeClient> m_chromeClient;
     OwnPtr<Page> m_page;
diff --git a/Source/core/svg/graphics/SVGImageCache.cpp b/Source/core/svg/graphics/SVGImageCache.cpp
index 4086f69..6b5e5a2 100644
--- a/Source/core/svg/graphics/SVGImageCache.cpp
+++ b/Source/core/svg/graphics/SVGImageCache.cpp
@@ -21,7 +21,7 @@
 #include "config.h"
 #include "core/svg/graphics/SVGImageCache.h"
 
-#include "core/loader/cache/CachedImage.h"
+#include "core/loader/cache/ImageResource.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/platform/graphics/GraphicsContext.h"
@@ -43,7 +43,7 @@
     m_imageForContainerMap.clear();
 }
 
-void SVGImageCache::removeClientFromCache(const CachedImageClient* client)
+void SVGImageCache::removeClientFromCache(const ImageResourceClient* client)
 {
     ASSERT(client);
 
@@ -51,7 +51,7 @@
         m_imageForContainerMap.remove(client);
 }
 
-void SVGImageCache::setContainerSizeForRenderer(const CachedImageClient* client, const IntSize& containerSize, float containerZoom)
+void SVGImageCache::setContainerSizeForRenderer(const ImageResourceClient* client, const IntSize& containerSize, float containerZoom)
 {
     ASSERT(client);
     ASSERT(!containerSize.isEmpty());
diff --git a/Source/core/svg/graphics/SVGImageCache.h b/Source/core/svg/graphics/SVGImageCache.h
index 6a793a9..b2aef4c 100644
--- a/Source/core/svg/graphics/SVGImageCache.h
+++ b/Source/core/svg/graphics/SVGImageCache.h
@@ -29,8 +29,8 @@
 
 namespace WebCore {
 
-class CachedImage;
-class CachedImageClient;
+class ImageResource;
+class ImageResourceClient;
 class ImageBuffer;
 class SVGImage;
 class SVGImageForContainer;
@@ -46,9 +46,9 @@
         return adoptPtr(new SVGImageCache(image));
     }
 
-    void removeClientFromCache(const CachedImageClient*);
+    void removeClientFromCache(const ImageResourceClient*);
 
-    void setContainerSizeForRenderer(const CachedImageClient*, const IntSize&, float);
+    void setContainerSizeForRenderer(const ImageResourceClient*, const IntSize&, float);
     IntSize imageSizeForRenderer(const RenderObject*) const;
 
     Image* imageForRenderer(const RenderObject*);
@@ -56,7 +56,7 @@
 private:
     SVGImageCache(SVGImage*);
 
-    typedef HashMap<const CachedImageClient*, RefPtr<SVGImageForContainer> > ImageForContainerMap;
+    typedef HashMap<const ImageResourceClient*, RefPtr<SVGImageForContainer> > ImageForContainerMap;
 
     SVGImage* m_svgImage;
     ImageForContainerMap m_imageForContainerMap;
diff --git a/Source/core/svg/graphics/SVGImageForContainer.cpp b/Source/core/svg/graphics/SVGImageForContainer.cpp
index 0b21d90..27f9a94 100644
--- a/Source/core/svg/graphics/SVGImageForContainer.cpp
+++ b/Source/core/svg/graphics/SVGImageForContainer.cpp
@@ -42,9 +42,9 @@
 }
 
 void SVGImageForContainer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale,
-    const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, BlendMode)
+    const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, BlendMode blendMode)
 {
-    m_image->drawPatternForContainer(context, m_containerSize, m_zoom, srcRect, scale, phase, compositeOp, dstRect);
+    m_image->drawPatternForContainer(context, m_containerSize, m_zoom, srcRect, scale, phase, compositeOp, dstRect, blendMode);
 }
 
 PassRefPtr<NativeImageSkia> SVGImageForContainer::nativeImageForCurrentFrame()
diff --git a/Source/core/svg/graphics/filters/SVGFEImage.cpp b/Source/core/svg/graphics/filters/SVGFEImage.cpp
index c7d753e..0ba43d5 100644
--- a/Source/core/svg/graphics/filters/SVGFEImage.cpp
+++ b/Source/core/svg/graphics/filters/SVGFEImage.cpp
@@ -157,7 +157,7 @@
     return ts;
 }
 
-SkImageFilter* FEImage::createImageFilter(SkiaImageFilterBuilder* builder)
+PassRefPtr<SkImageFilter> FEImage::createImageFilter(SkiaImageFilterBuilder* builder)
 {
     if (!m_image)
         return 0;
@@ -165,7 +165,7 @@
     if (!m_image->nativeImageForCurrentFrame())
         return 0;
 
-    return new SkBitmapSource(m_image->nativeImageForCurrentFrame()->bitmap());
+    return adoptRef(new SkBitmapSource(m_image->nativeImageForCurrentFrame()->bitmap()));
 }
 
 } // namespace WebCore
diff --git a/Source/core/svg/graphics/filters/SVGFEImage.h b/Source/core/svg/graphics/filters/SVGFEImage.h
index 50486d0..1566b7a 100644
--- a/Source/core/svg/graphics/filters/SVGFEImage.h
+++ b/Source/core/svg/graphics/filters/SVGFEImage.h
@@ -43,7 +43,7 @@
     virtual FilterEffectType filterEffectType() const { return FilterEffectTypeImage; }
 
     virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+    virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
 private:
     virtual ~FEImage() { }
diff --git a/Source/core/testing/Internals.cpp b/Source/core/testing/Internals.cpp
index f29fa25..dba52a6 100644
--- a/Source/core/testing/Internals.cpp
+++ b/Source/core/testing/Internals.cpp
@@ -705,7 +705,7 @@
         return;
     }
 
-    return element->setPseudo(id);
+    return element->setPart(id);
 }
 
 String Internals::visiblePlaceholder(Element* element)
@@ -1815,17 +1815,6 @@
     page->setDeviceScaleFactor(scaleFactor);
 }
 
-void Internals::setPageScaleFactor(float scaleFactor, int x, int y, ExceptionState& es)
-{
-    Document* document = contextDocument();
-    if (!document || !document->page()) {
-        es.throwDOMException(InvalidAccessError);
-        return;
-    }
-    Page* page = document->page();
-    page->setPageScaleFactor(scaleFactor, IntPoint(x, y));
-}
-
 void Internals::setIsCursorVisible(Document* document, bool isVisible, ExceptionState& es)
 {
     if (!document || !document->page()) {
diff --git a/Source/core/testing/Internals.h b/Source/core/testing/Internals.h
index e76a0a3..bde21e2 100644
--- a/Source/core/testing/Internals.h
+++ b/Source/core/testing/Internals.h
@@ -255,7 +255,6 @@
     String pageSizeAndMarginsInPixels(int, int, int, int, int, int, int, ExceptionState& = ASSERT_NO_EXCEPTION) const;
 
     void setDeviceScaleFactor(float scaleFactor, ExceptionState&);
-    void setPageScaleFactor(float scaleFactor, int x, int y, ExceptionState&);
 
     void setIsCursorVisible(Document*, bool, ExceptionState&);
 
diff --git a/Source/core/testing/Internals.idl b/Source/core/testing/Internals.idl
index 14f1d59..d521c04 100644
--- a/Source/core/testing/Internals.idl
+++ b/Source/core/testing/Internals.idl
@@ -215,7 +215,6 @@
     [RaisesException] DOMString pageSizeAndMarginsInPixels(long pageIndex, long width, long height, long marginTop, long marginRight, long marginBottom, long marginLeft);
 
     [RaisesException] void setDeviceScaleFactor(float scaleFactor);
-    [RaisesException] void setPageScaleFactor(float scaleFactor, long x, long y);
 
     [RaisesException] void setIsCursorVisible(Document document, boolean isVisible);
 
diff --git a/Source/core/webcore_derived.target.darwin-arm.mk b/Source/core/webcore_derived.target.darwin-arm.mk
index 31e8d4b..f634b2e 100644
--- a/Source/core/webcore_derived.target.darwin-arm.mk
+++ b/Source/core/webcore_derived.target.darwin-arm.mk
@@ -426,6 +426,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -593,6 +594,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_derived.target.darwin-mips.mk b/Source/core/webcore_derived.target.darwin-mips.mk
index c759cbc..c2d7789 100644
--- a/Source/core/webcore_derived.target.darwin-mips.mk
+++ b/Source/core/webcore_derived.target.darwin-mips.mk
@@ -426,6 +426,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -593,6 +594,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_derived.target.darwin-x86.mk b/Source/core/webcore_derived.target.darwin-x86.mk
index d408565..01053b5 100644
--- a/Source/core/webcore_derived.target.darwin-x86.mk
+++ b/Source/core/webcore_derived.target.darwin-x86.mk
@@ -428,6 +428,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -598,6 +599,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_derived.target.linux-arm.mk b/Source/core/webcore_derived.target.linux-arm.mk
index 31e8d4b..f634b2e 100644
--- a/Source/core/webcore_derived.target.linux-arm.mk
+++ b/Source/core/webcore_derived.target.linux-arm.mk
@@ -426,6 +426,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -593,6 +594,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_derived.target.linux-mips.mk b/Source/core/webcore_derived.target.linux-mips.mk
index c759cbc..c2d7789 100644
--- a/Source/core/webcore_derived.target.linux-mips.mk
+++ b/Source/core/webcore_derived.target.linux-mips.mk
@@ -426,6 +426,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -593,6 +594,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_derived.target.linux-x86.mk b/Source/core/webcore_derived.target.linux-x86.mk
index d408565..01053b5 100644
--- a/Source/core/webcore_derived.target.linux-x86.mk
+++ b/Source/core/webcore_derived.target.linux-x86.mk
@@ -428,6 +428,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -598,6 +599,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_dom.target.darwin-arm.mk b/Source/core/webcore_dom.target.darwin-arm.mk
index 4074e0d..67301bf 100644
--- a/Source/core/webcore_dom.target.darwin-arm.mk
+++ b/Source/core/webcore_dom.target.darwin-arm.mk
@@ -266,6 +266,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -424,6 +425,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_dom.target.darwin-mips.mk b/Source/core/webcore_dom.target.darwin-mips.mk
index cca3ca1..1f9351d 100644
--- a/Source/core/webcore_dom.target.darwin-mips.mk
+++ b/Source/core/webcore_dom.target.darwin-mips.mk
@@ -266,6 +266,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -424,6 +425,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_dom.target.darwin-x86.mk b/Source/core/webcore_dom.target.darwin-x86.mk
index 513b6df..c466023 100644
--- a/Source/core/webcore_dom.target.darwin-x86.mk
+++ b/Source/core/webcore_dom.target.darwin-x86.mk
@@ -268,6 +268,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -429,6 +430,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_dom.target.linux-arm.mk b/Source/core/webcore_dom.target.linux-arm.mk
index 4074e0d..67301bf 100644
--- a/Source/core/webcore_dom.target.linux-arm.mk
+++ b/Source/core/webcore_dom.target.linux-arm.mk
@@ -266,6 +266,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -424,6 +425,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_dom.target.linux-mips.mk b/Source/core/webcore_dom.target.linux-mips.mk
index cca3ca1..1f9351d 100644
--- a/Source/core/webcore_dom.target.linux-mips.mk
+++ b/Source/core/webcore_dom.target.linux-mips.mk
@@ -266,6 +266,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -424,6 +425,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_dom.target.linux-x86.mk b/Source/core/webcore_dom.target.linux-x86.mk
index 513b6df..c466023 100644
--- a/Source/core/webcore_dom.target.linux-x86.mk
+++ b/Source/core/webcore_dom.target.linux-x86.mk
@@ -268,6 +268,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -429,6 +430,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_html.target.darwin-arm.mk b/Source/core/webcore_html.target.darwin-arm.mk
index 66ee58b..934138a 100644
--- a/Source/core/webcore_html.target.darwin-arm.mk
+++ b/Source/core/webcore_html.target.darwin-arm.mk
@@ -87,6 +87,7 @@
 	third_party/WebKit/Source/core/html/HTMLImageLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -145,6 +146,7 @@
 	third_party/WebKit/Source/core/html/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
 	third_party/WebKit/Source/core/html/LabelsNodeList.cpp \
+	third_party/WebKit/Source/core/html/LinkImport.cpp \
 	third_party/WebKit/Source/core/html/LinkRelAttribute.cpp \
 	third_party/WebKit/Source/core/html/LinkResource.cpp \
 	third_party/WebKit/Source/core/html/MediaController.cpp \
@@ -368,6 +370,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -526,6 +529,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_html.target.darwin-mips.mk b/Source/core/webcore_html.target.darwin-mips.mk
index 2c44b8a..b0f57a8 100644
--- a/Source/core/webcore_html.target.darwin-mips.mk
+++ b/Source/core/webcore_html.target.darwin-mips.mk
@@ -87,6 +87,7 @@
 	third_party/WebKit/Source/core/html/HTMLImageLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -145,6 +146,7 @@
 	third_party/WebKit/Source/core/html/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
 	third_party/WebKit/Source/core/html/LabelsNodeList.cpp \
+	third_party/WebKit/Source/core/html/LinkImport.cpp \
 	third_party/WebKit/Source/core/html/LinkRelAttribute.cpp \
 	third_party/WebKit/Source/core/html/LinkResource.cpp \
 	third_party/WebKit/Source/core/html/MediaController.cpp \
@@ -368,6 +370,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -526,6 +529,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_html.target.darwin-x86.mk b/Source/core/webcore_html.target.darwin-x86.mk
index 5f8355b..c4b1ca1 100644
--- a/Source/core/webcore_html.target.darwin-x86.mk
+++ b/Source/core/webcore_html.target.darwin-x86.mk
@@ -87,6 +87,7 @@
 	third_party/WebKit/Source/core/html/HTMLImageLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -145,6 +146,7 @@
 	third_party/WebKit/Source/core/html/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
 	third_party/WebKit/Source/core/html/LabelsNodeList.cpp \
+	third_party/WebKit/Source/core/html/LinkImport.cpp \
 	third_party/WebKit/Source/core/html/LinkRelAttribute.cpp \
 	third_party/WebKit/Source/core/html/LinkResource.cpp \
 	third_party/WebKit/Source/core/html/MediaController.cpp \
@@ -370,6 +372,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -531,6 +534,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_html.target.linux-arm.mk b/Source/core/webcore_html.target.linux-arm.mk
index 66ee58b..934138a 100644
--- a/Source/core/webcore_html.target.linux-arm.mk
+++ b/Source/core/webcore_html.target.linux-arm.mk
@@ -87,6 +87,7 @@
 	third_party/WebKit/Source/core/html/HTMLImageLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -145,6 +146,7 @@
 	third_party/WebKit/Source/core/html/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
 	third_party/WebKit/Source/core/html/LabelsNodeList.cpp \
+	third_party/WebKit/Source/core/html/LinkImport.cpp \
 	third_party/WebKit/Source/core/html/LinkRelAttribute.cpp \
 	third_party/WebKit/Source/core/html/LinkResource.cpp \
 	third_party/WebKit/Source/core/html/MediaController.cpp \
@@ -368,6 +370,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -526,6 +529,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_html.target.linux-mips.mk b/Source/core/webcore_html.target.linux-mips.mk
index 2c44b8a..b0f57a8 100644
--- a/Source/core/webcore_html.target.linux-mips.mk
+++ b/Source/core/webcore_html.target.linux-mips.mk
@@ -87,6 +87,7 @@
 	third_party/WebKit/Source/core/html/HTMLImageLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -145,6 +146,7 @@
 	third_party/WebKit/Source/core/html/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
 	third_party/WebKit/Source/core/html/LabelsNodeList.cpp \
+	third_party/WebKit/Source/core/html/LinkImport.cpp \
 	third_party/WebKit/Source/core/html/LinkRelAttribute.cpp \
 	third_party/WebKit/Source/core/html/LinkResource.cpp \
 	third_party/WebKit/Source/core/html/MediaController.cpp \
@@ -368,6 +370,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -526,6 +529,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_html.target.linux-x86.mk b/Source/core/webcore_html.target.linux-x86.mk
index 5f8355b..c4b1ca1 100644
--- a/Source/core/webcore_html.target.linux-x86.mk
+++ b/Source/core/webcore_html.target.linux-x86.mk
@@ -87,6 +87,7 @@
 	third_party/WebKit/Source/core/html/HTMLImageLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -145,6 +146,7 @@
 	third_party/WebKit/Source/core/html/InputTypeNames.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
 	third_party/WebKit/Source/core/html/LabelsNodeList.cpp \
+	third_party/WebKit/Source/core/html/LinkImport.cpp \
 	third_party/WebKit/Source/core/html/LinkRelAttribute.cpp \
 	third_party/WebKit/Source/core/html/LinkResource.cpp \
 	third_party/WebKit/Source/core/html/MediaController.cpp \
@@ -370,6 +372,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -531,6 +534,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform.target.darwin-arm.mk b/Source/core/webcore_platform.target.darwin-arm.mk
index 13dd1db..c5a1a78 100644
--- a/Source/core/webcore_platform.target.darwin-arm.mk
+++ b/Source/core/webcore_platform.target.darwin-arm.mk
@@ -63,7 +63,6 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
-	third_party/WebKit/Source/core/platform/ScrollbarThemeComposite.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -138,6 +137,7 @@
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -216,7 +216,6 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/DropShadowImageFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp \
@@ -260,6 +259,7 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
+	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
@@ -417,6 +417,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -576,6 +577,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform.target.darwin-mips.mk b/Source/core/webcore_platform.target.darwin-mips.mk
index c45c3b4..72b9556 100644
--- a/Source/core/webcore_platform.target.darwin-mips.mk
+++ b/Source/core/webcore_platform.target.darwin-mips.mk
@@ -63,7 +63,6 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
-	third_party/WebKit/Source/core/platform/ScrollbarThemeComposite.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -138,6 +137,7 @@
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -216,7 +216,6 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/DropShadowImageFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp \
@@ -260,6 +259,7 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
+	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
@@ -417,6 +417,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -576,6 +577,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform.target.darwin-x86.mk b/Source/core/webcore_platform.target.darwin-x86.mk
index 75ddd31..c1048db 100644
--- a/Source/core/webcore_platform.target.darwin-x86.mk
+++ b/Source/core/webcore_platform.target.darwin-x86.mk
@@ -63,7 +63,6 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
-	third_party/WebKit/Source/core/platform/ScrollbarThemeComposite.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -138,6 +137,7 @@
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -216,7 +216,6 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/DropShadowImageFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp \
@@ -260,6 +259,7 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
+	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
@@ -419,6 +419,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -581,6 +582,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform.target.linux-arm.mk b/Source/core/webcore_platform.target.linux-arm.mk
index 13dd1db..c5a1a78 100644
--- a/Source/core/webcore_platform.target.linux-arm.mk
+++ b/Source/core/webcore_platform.target.linux-arm.mk
@@ -63,7 +63,6 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
-	third_party/WebKit/Source/core/platform/ScrollbarThemeComposite.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -138,6 +137,7 @@
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -216,7 +216,6 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/DropShadowImageFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp \
@@ -260,6 +259,7 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
+	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
@@ -417,6 +417,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -576,6 +577,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform.target.linux-mips.mk b/Source/core/webcore_platform.target.linux-mips.mk
index c45c3b4..72b9556 100644
--- a/Source/core/webcore_platform.target.linux-mips.mk
+++ b/Source/core/webcore_platform.target.linux-mips.mk
@@ -63,7 +63,6 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
-	third_party/WebKit/Source/core/platform/ScrollbarThemeComposite.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -138,6 +137,7 @@
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -216,7 +216,6 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/DropShadowImageFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp \
@@ -260,6 +259,7 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
+	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
@@ -417,6 +417,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -576,6 +577,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform.target.linux-x86.mk b/Source/core/webcore_platform.target.linux-x86.mk
index 75ddd31..c1048db 100644
--- a/Source/core/webcore_platform.target.linux-x86.mk
+++ b/Source/core/webcore_platform.target.linux-x86.mk
@@ -63,7 +63,6 @@
 	third_party/WebKit/Source/core/platform/ScrollableArea.cpp \
 	third_party/WebKit/Source/core/platform/Scrollbar.cpp \
 	third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp \
-	third_party/WebKit/Source/core/platform/ScrollbarThemeComposite.cpp \
 	third_party/WebKit/Source/core/platform/SecureTextInput.cpp \
 	third_party/WebKit/Source/core/platform/SharedBuffer.cpp \
 	third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp \
@@ -138,6 +137,7 @@
 	third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/platform/chromium/ScrollbarThemeChromiumOverlay.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp \
@@ -216,7 +216,6 @@
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp \
-	third_party/WebKit/Source/core/platform/graphics/filters/DropShadowImageFilter.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp \
 	third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp \
@@ -260,6 +259,7 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
+	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
@@ -419,6 +419,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -581,6 +582,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-arm.mk b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
index db08d99..1ebff00 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
@@ -118,6 +118,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -276,6 +277,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-mips.mk b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
index 6c3d0b4..dfe6926 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
@@ -118,6 +118,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -276,6 +277,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-x86.mk b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
index 52e8a64..65e94d1 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
@@ -120,6 +120,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -281,6 +282,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform_geometry.target.linux-arm.mk b/Source/core/webcore_platform_geometry.target.linux-arm.mk
index db08d99..1ebff00 100644
--- a/Source/core/webcore_platform_geometry.target.linux-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-arm.mk
@@ -118,6 +118,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -276,6 +277,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform_geometry.target.linux-mips.mk b/Source/core/webcore_platform_geometry.target.linux-mips.mk
index 6c3d0b4..dfe6926 100644
--- a/Source/core/webcore_platform_geometry.target.linux-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-mips.mk
@@ -118,6 +118,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -276,6 +277,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_platform_geometry.target.linux-x86.mk b/Source/core/webcore_platform_geometry.target.linux-x86.mk
index 52e8a64..65e94d1 100644
--- a/Source/core/webcore_platform_geometry.target.linux-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-x86.mk
@@ -120,6 +120,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -281,6 +282,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_remaining.target.darwin-arm.mk b/Source/core/webcore_remaining.target.darwin-arm.mk
index 02c5c0f..426bdfb 100644
--- a/Source/core/webcore_remaining.target.darwin-arm.mk
+++ b/Source/core/webcore_remaining.target.darwin-arm.mk
@@ -166,6 +166,7 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
@@ -198,6 +199,7 @@
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
 	third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp \
+	third_party/WebKit/Source/core/editing/InputMethodController.cpp \
 	third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertListCommand.cpp \
@@ -340,7 +342,6 @@
 	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
@@ -352,19 +353,19 @@
 	third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedCSSStyleSheet.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedDocument.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedFont.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedImage.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedRawResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
 	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedScript.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedShader.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedTextTrack.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedXSLStyleSheet.cpp \
+	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
@@ -586,6 +587,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -745,6 +747,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_remaining.target.darwin-mips.mk b/Source/core/webcore_remaining.target.darwin-mips.mk
index 971d610..e69d7e0 100644
--- a/Source/core/webcore_remaining.target.darwin-mips.mk
+++ b/Source/core/webcore_remaining.target.darwin-mips.mk
@@ -166,6 +166,7 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
@@ -198,6 +199,7 @@
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
 	third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp \
+	third_party/WebKit/Source/core/editing/InputMethodController.cpp \
 	third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertListCommand.cpp \
@@ -340,7 +342,6 @@
 	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
@@ -352,19 +353,19 @@
 	third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedCSSStyleSheet.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedDocument.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedFont.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedImage.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedRawResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
 	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedScript.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedShader.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedTextTrack.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedXSLStyleSheet.cpp \
+	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
@@ -586,6 +587,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -745,6 +747,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_remaining.target.darwin-x86.mk b/Source/core/webcore_remaining.target.darwin-x86.mk
index caeebe8..d244b5e 100644
--- a/Source/core/webcore_remaining.target.darwin-x86.mk
+++ b/Source/core/webcore_remaining.target.darwin-x86.mk
@@ -166,6 +166,7 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
@@ -198,6 +199,7 @@
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
 	third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp \
+	third_party/WebKit/Source/core/editing/InputMethodController.cpp \
 	third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertListCommand.cpp \
@@ -340,7 +342,6 @@
 	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
@@ -352,19 +353,19 @@
 	third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedCSSStyleSheet.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedDocument.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedFont.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedImage.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedRawResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
 	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedScript.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedShader.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedTextTrack.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedXSLStyleSheet.cpp \
+	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
@@ -588,6 +589,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -750,6 +752,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_remaining.target.linux-arm.mk b/Source/core/webcore_remaining.target.linux-arm.mk
index 02c5c0f..426bdfb 100644
--- a/Source/core/webcore_remaining.target.linux-arm.mk
+++ b/Source/core/webcore_remaining.target.linux-arm.mk
@@ -166,6 +166,7 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
@@ -198,6 +199,7 @@
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
 	third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp \
+	third_party/WebKit/Source/core/editing/InputMethodController.cpp \
 	third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertListCommand.cpp \
@@ -340,7 +342,6 @@
 	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
@@ -352,19 +353,19 @@
 	third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedCSSStyleSheet.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedDocument.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedFont.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedImage.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedRawResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
 	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedScript.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedShader.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedTextTrack.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedXSLStyleSheet.cpp \
+	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
@@ -586,6 +587,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -745,6 +747,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_remaining.target.linux-mips.mk b/Source/core/webcore_remaining.target.linux-mips.mk
index 971d610..e69d7e0 100644
--- a/Source/core/webcore_remaining.target.linux-mips.mk
+++ b/Source/core/webcore_remaining.target.linux-mips.mk
@@ -166,6 +166,7 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
@@ -198,6 +199,7 @@
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
 	third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp \
+	third_party/WebKit/Source/core/editing/InputMethodController.cpp \
 	third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertListCommand.cpp \
@@ -340,7 +342,6 @@
 	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
@@ -352,19 +353,19 @@
 	third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedCSSStyleSheet.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedDocument.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedFont.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedImage.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedRawResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
 	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedScript.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedShader.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedTextTrack.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedXSLStyleSheet.cpp \
+	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
@@ -586,6 +587,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -745,6 +747,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_remaining.target.linux-x86.mk b/Source/core/webcore_remaining.target.linux-x86.mk
index caeebe8..d244b5e 100644
--- a/Source/core/webcore_remaining.target.linux-x86.mk
+++ b/Source/core/webcore_remaining.target.linux-x86.mk
@@ -166,6 +166,7 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
@@ -198,6 +199,7 @@
 	third_party/WebKit/Source/core/editing/FrameSelection.cpp \
 	third_party/WebKit/Source/core/editing/HTMLInterchange.cpp \
 	third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp \
+	third_party/WebKit/Source/core/editing/InputMethodController.cpp \
 	third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp \
 	third_party/WebKit/Source/core/editing/InsertListCommand.cpp \
@@ -340,7 +342,6 @@
 	third_party/WebKit/Source/core/loader/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/loader/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
@@ -352,19 +353,19 @@
 	third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp \
 	third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedCSSStyleSheet.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedDocument.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedFont.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedImage.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedRawResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/CSSStyleSheetResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/DocumentResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/FontResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ImageResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/RawResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/Resource.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/loader/cache/ResourceFetcher.cpp \
 	third_party/WebKit/Source/core/loader/cache/FetchRequest.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedScript.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedShader.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedTextTrack.cpp \
-	third_party/WebKit/Source/core/loader/cache/CachedXSLStyleSheet.cpp \
+	third_party/WebKit/Source/core/loader/cache/ScriptResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/ShaderResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/TextTrackResource.cpp \
+	third_party/WebKit/Source/core/loader/cache/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/loader/cache/MemoryCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
 	third_party/WebKit/Source/core/page/BarProp.cpp \
@@ -588,6 +589,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -750,6 +752,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_rendering.target.darwin-arm.mk b/Source/core/webcore_rendering.target.darwin-arm.mk
index 39aadad..834b662 100644
--- a/Source/core/webcore_rendering.target.darwin-arm.mk
+++ b/Source/core/webcore_rendering.target.darwin-arm.mk
@@ -155,9 +155,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImage.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedShader.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
@@ -257,6 +257,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -415,6 +416,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_rendering.target.darwin-mips.mk b/Source/core/webcore_rendering.target.darwin-mips.mk
index cf0c5e9..b2a8aa6 100644
--- a/Source/core/webcore_rendering.target.darwin-mips.mk
+++ b/Source/core/webcore_rendering.target.darwin-mips.mk
@@ -155,9 +155,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImage.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedShader.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
@@ -257,6 +257,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -415,6 +416,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_rendering.target.darwin-x86.mk b/Source/core/webcore_rendering.target.darwin-x86.mk
index 96c2c28..8c708e1 100644
--- a/Source/core/webcore_rendering.target.darwin-x86.mk
+++ b/Source/core/webcore_rendering.target.darwin-x86.mk
@@ -155,9 +155,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImage.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedShader.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
@@ -260,6 +260,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -422,6 +423,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_rendering.target.linux-arm.mk b/Source/core/webcore_rendering.target.linux-arm.mk
index 39aadad..834b662 100644
--- a/Source/core/webcore_rendering.target.linux-arm.mk
+++ b/Source/core/webcore_rendering.target.linux-arm.mk
@@ -155,9 +155,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImage.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedShader.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
@@ -257,6 +257,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -415,6 +416,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_rendering.target.linux-mips.mk b/Source/core/webcore_rendering.target.linux-mips.mk
index cf0c5e9..b2a8aa6 100644
--- a/Source/core/webcore_rendering.target.linux-mips.mk
+++ b/Source/core/webcore_rendering.target.linux-mips.mk
@@ -155,9 +155,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImage.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedShader.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
@@ -257,6 +257,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -415,6 +416,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_rendering.target.linux-x86.mk b/Source/core/webcore_rendering.target.linux-x86.mk
index 96c2c28..8c708e1 100644
--- a/Source/core/webcore_rendering.target.linux-x86.mk
+++ b/Source/core/webcore_rendering.target.linux-x86.mk
@@ -155,9 +155,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImage.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCachedShader.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
@@ -260,6 +260,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -422,6 +423,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_svg.target.darwin-arm.mk b/Source/core/webcore_svg.target.darwin-arm.mk
index 9608503..8440c4b 100644
--- a/Source/core/webcore_svg.target.darwin-arm.mk
+++ b/Source/core/webcore_svg.target.darwin-arm.mk
@@ -327,6 +327,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -485,6 +486,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_svg.target.darwin-mips.mk b/Source/core/webcore_svg.target.darwin-mips.mk
index f4a0890..173daed 100644
--- a/Source/core/webcore_svg.target.darwin-mips.mk
+++ b/Source/core/webcore_svg.target.darwin-mips.mk
@@ -327,6 +327,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -485,6 +486,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_svg.target.darwin-x86.mk b/Source/core/webcore_svg.target.darwin-x86.mk
index 669653b..48a09cf 100644
--- a/Source/core/webcore_svg.target.darwin-x86.mk
+++ b/Source/core/webcore_svg.target.darwin-x86.mk
@@ -329,6 +329,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -490,6 +491,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_svg.target.linux-arm.mk b/Source/core/webcore_svg.target.linux-arm.mk
index 9608503..8440c4b 100644
--- a/Source/core/webcore_svg.target.linux-arm.mk
+++ b/Source/core/webcore_svg.target.linux-arm.mk
@@ -327,6 +327,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -485,6 +486,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_svg.target.linux-mips.mk b/Source/core/webcore_svg.target.linux-mips.mk
index f4a0890..173daed 100644
--- a/Source/core/webcore_svg.target.linux-mips.mk
+++ b/Source/core/webcore_svg.target.linux-mips.mk
@@ -327,6 +327,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -485,6 +486,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/webcore_svg.target.linux-x86.mk b/Source/core/webcore_svg.target.linux-x86.mk
index 669653b..48a09cf 100644
--- a/Source/core/webcore_svg.target.linux-x86.mk
+++ b/Source/core/webcore_svg.target.linux-x86.mk
@@ -329,6 +329,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
@@ -490,6 +491,7 @@
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DUSE_CHROMIUM_SKIA' \
 	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
 	'-DLIBXML_STATIC' \
diff --git a/Source/core/workers/AbstractWorker.idl b/Source/core/workers/AbstractWorker.idl
index 2b6e1f9..9c13c6f 100644
--- a/Source/core/workers/AbstractWorker.idl
+++ b/Source/core/workers/AbstractWorker.idl
@@ -33,6 +33,6 @@
     NoInterfaceObject,
     LegacyImplementedInBaseClass
 ] interface AbstractWorker {
-    attribute EventListener onerror;
+    attribute EventHandler onerror;
 };
 
diff --git a/Source/core/workers/DedicatedWorkerGlobalScope.idl b/Source/core/workers/DedicatedWorkerGlobalScope.idl
index 7cb9399..659a5f5 100644
--- a/Source/core/workers/DedicatedWorkerGlobalScope.idl
+++ b/Source/core/workers/DedicatedWorkerGlobalScope.idl
@@ -32,6 +32,6 @@
     GlobalContext=DedicatedWorkerGlobalScope
 ] interface DedicatedWorkerGlobalScope : WorkerGlobalScope {
     [Custom, RaisesException] void postMessage(any message, optional Array messagePorts);
-    attribute EventListener onmessage;
+    attribute EventHandler onmessage;
 };
 
diff --git a/Source/core/workers/SharedWorkerGlobalScope.idl b/Source/core/workers/SharedWorkerGlobalScope.idl
index 4c930a4..dcb59b8 100644
--- a/Source/core/workers/SharedWorkerGlobalScope.idl
+++ b/Source/core/workers/SharedWorkerGlobalScope.idl
@@ -32,6 +32,6 @@
     GlobalContext=SharedWorkerGlobalScope
 ] interface SharedWorkerGlobalScope : WorkerGlobalScope {
     readonly attribute DOMString name;
-             attribute EventListener onconnect;
+             attribute EventHandler onconnect;
 };
 
diff --git a/Source/core/workers/Worker.idl b/Source/core/workers/Worker.idl
index 34aa4be..40567a7 100644
--- a/Source/core/workers/Worker.idl
+++ b/Source/core/workers/Worker.idl
@@ -32,7 +32,7 @@
     ActiveDOMObject
 ] interface Worker : EventTarget {
 
-    attribute EventListener onmessage;
+    attribute EventHandler onmessage;
 
     [Custom, RaisesException] void postMessage(SerializedScriptValue message, optional Array messagePorts);
     void terminate();
diff --git a/Source/core/workers/WorkerGlobalScope.cpp b/Source/core/workers/WorkerGlobalScope.cpp
index 263c9ec..f80e1ff 100644
--- a/Source/core/workers/WorkerGlobalScope.cpp
+++ b/Source/core/workers/WorkerGlobalScope.cpp
@@ -214,10 +214,10 @@
 
         InspectorInstrumentation::scriptImported(scriptExecutionContext(), scriptLoader->identifier(), scriptLoader->script());
 
-        ScriptValue exception;
-        m_script->evaluate(ScriptSourceCode(scriptLoader->script(), scriptLoader->responseURL()), &exception);
-        if (!exception.hasNoValue()) {
-            m_script->setException(exception);
+        RefPtr<ErrorEvent> errorEvent;
+        m_script->evaluate(ScriptSourceCode(scriptLoader->script(), scriptLoader->responseURL()), &errorEvent);
+        if (errorEvent) {
+            m_script->rethrowExceptionFromImportedScript(errorEvent.release());
             return;
         }
     }
diff --git a/Source/core/workers/WorkerGlobalScope.idl b/Source/core/workers/WorkerGlobalScope.idl
index e395d34..87c3594 100644
--- a/Source/core/workers/WorkerGlobalScope.idl
+++ b/Source/core/workers/WorkerGlobalScope.idl
@@ -34,7 +34,7 @@
     [Replaceable] readonly attribute WorkerGlobalScope self;
     [Replaceable] readonly attribute WorkerLocation location;
     void close();
-    attribute EventListener onerror;
+    attribute EventHandler onerror;
 
     // WorkerUtils
     [Custom] void importScripts(/*[Variadic] in DOMString urls */);
diff --git a/Source/core/xml/XMLHttpRequest.cpp b/Source/core/xml/XMLHttpRequest.cpp
index d16f22b..e65a4a7 100644
--- a/Source/core/xml/XMLHttpRequest.cpp
+++ b/Source/core/xml/XMLHttpRequest.cpp
@@ -468,13 +468,12 @@
     }
 
     if (!isAllowedHTTPMethod(method)) {
-        es.throwDOMException(SecurityError);
+        es.throwDOMException(SecurityError, "'XMLHttpRequest.open' does not support the '" + method + "' method.");
         return;
     }
 
     if (!ContentSecurityPolicy::shouldBypassMainWorld(scriptExecutionContext()) && !scriptExecutionContext()->contentSecurityPolicy()->allowConnectToSource(url)) {
-        // FIXME: Should this be throwing an exception?
-        es.throwDOMException(SecurityError);
+        es.throwDOMException(SecurityError, "Refused to connect to '" + url.elidedString() + "' because it violates the document's Content Security Policy.");
         return;
     }
 
@@ -595,7 +594,7 @@
     if (!body.isNull() && areMethodAndURLValidForSend()) {
         String contentType = getRequestHeader("Content-Type");
         if (contentType.isEmpty()) {
-            setRequestHeaderInternal("Content-Type", "application/xml");
+            setRequestHeaderInternal("Content-Type", "text/plain;charset=UTF-8");
         } else {
             replaceCharsetInMediaType(contentType, "UTF-8");
             m_requestHeaders.set("Content-Type", contentType);
@@ -647,7 +646,7 @@
 
         String contentType = getRequestHeader("Content-Type");
         if (contentType.isEmpty()) {
-            contentType = String(ASCIILiteral("multipart/form-data; boundary=")) + m_requestEntityBody->boundary().data();
+            contentType = String("multipart/form-data; boundary=") + m_requestEntityBody->boundary().data();
             setRequestHeaderInternal("Content-Type", contentType);
         }
     }
diff --git a/Source/core/xml/XMLHttpRequest.idl b/Source/core/xml/XMLHttpRequest.idl
index bad83ca..2c4f120 100644
--- a/Source/core/xml/XMLHttpRequest.idl
+++ b/Source/core/xml/XMLHttpRequest.idl
@@ -45,16 +45,16 @@
 ] interface XMLHttpRequest : EventTarget {
     // From XMLHttpRequestEventTarget
     // event handler attributes
-    attribute EventListener onabort;
-    attribute EventListener onerror;
-    attribute EventListener onload;
-    attribute EventListener onloadend;
-    attribute EventListener onloadstart;
-    attribute EventListener onprogress;
-    attribute EventListener ontimeout;
+    attribute EventHandler onabort;
+    attribute EventHandler onerror;
+    attribute EventHandler onload;
+    attribute EventHandler onloadend;
+    attribute EventHandler onloadstart;
+    attribute EventHandler onprogress;
+    attribute EventHandler ontimeout;
 
     // event handler attributes
-    attribute EventListener onreadystatechange;
+    attribute EventHandler onreadystatechange;
 
     // state
     const unsigned short UNSENT = 0;
diff --git a/Source/core/xml/XMLHttpRequestUpload.idl b/Source/core/xml/XMLHttpRequestUpload.idl
index d2170ed..eec9988 100644
--- a/Source/core/xml/XMLHttpRequestUpload.idl
+++ b/Source/core/xml/XMLHttpRequestUpload.idl
@@ -29,11 +29,11 @@
 interface XMLHttpRequestUpload : EventTarget {
     // From XMLHttpRequestEventTarget
     // event handler attributes
-    attribute EventListener onabort;
-    attribute EventListener onerror;
-    attribute EventListener onload;
-    attribute EventListener onloadend;
-    attribute EventListener onloadstart;
-    attribute EventListener onprogress;
+    attribute EventHandler onabort;
+    attribute EventHandler onerror;
+    attribute EventHandler onload;
+    attribute EventHandler onloadend;
+    attribute EventHandler onloadstart;
+    attribute EventHandler onprogress;
 };
 
diff --git a/Source/core/xml/XMLViewer.js b/Source/core/xml/XMLViewer.js
index 8615984..049779b 100644
--- a/Source/core/xml/XMLViewer.js
+++ b/Source/core/xml/XMLViewer.js
@@ -72,9 +72,6 @@
     var sourceXML = document.getElementById('webkit-xml-viewer-source-xml');
     if (!sourceXML)
         return; // Stop if some XML tree extension is already processing this document
-    //var style = document.head.firstChild;
-    //document.head.removeChild(style);
-    //document.head.appendChild(style);
     var root = document.getElementById('tree');
 
     for (var child = sourceXML.firstChild; child; child = child.nextSibling)
diff --git a/Source/core/xml/XSLImportRule.cpp b/Source/core/xml/XSLImportRule.cpp
index e728200..242303c 100644
--- a/Source/core/xml/XSLImportRule.cpp
+++ b/Source/core/xml/XSLImportRule.cpp
@@ -24,9 +24,9 @@
 
 #include "FetchInitiatorTypeNames.h"
 #include "core/dom/Document.h"
-#include "core/loader/cache/CachedXSLStyleSheet.h"
 #include "core/loader/cache/FetchRequest.h"
 #include "core/loader/cache/ResourceFetcher.h"
+#include "core/loader/cache/XSLStyleSheetResource.h"
 #include "core/xml/XSLStyleSheet.h"
 
 namespace WebCore {
@@ -34,7 +34,7 @@
 XSLImportRule::XSLImportRule(XSLStyleSheet* parent, const String& href)
     : m_parentStyleSheet(parent)
     , m_strHref(href)
-    , m_cachedSheet(0)
+    , m_resource(0)
     , m_loading(false)
 {
 }
@@ -44,8 +44,8 @@
     if (m_styleSheet)
         m_styleSheet->setParentStyleSheet(0);
 
-    if (m_cachedSheet)
-        m_cachedSheet->removeClient(this);
+    if (m_resource)
+        m_resource->removeClient(this);
 }
 
 void XSLImportRule::setXSLStyleSheet(const String& href, const KURL& baseURL, const String& sheet)
@@ -99,10 +99,10 @@
     }
 
     FetchRequest request(ResourceRequest(fetcher->document()->completeURL(absHref)), FetchInitiatorTypeNames::xml);
-    m_cachedSheet = fetcher->requestXSLStyleSheet(request);
+    m_resource = fetcher->requestXSLStyleSheet(request);
 
-    if (m_cachedSheet) {
-        m_cachedSheet->addClient(this);
+    if (m_resource) {
+        m_resource->addClient(this);
 
         // If the imported sheet is in the cache, then setXSLStyleSheet gets called,
         // and the sheet even gets parsed (via parseString).  In this case we have
diff --git a/Source/core/xml/XSLImportRule.h b/Source/core/xml/XSLImportRule.h
index be04012..63355d1 100644
--- a/Source/core/xml/XSLImportRule.h
+++ b/Source/core/xml/XSLImportRule.h
@@ -23,16 +23,16 @@
 #ifndef XSLImportRule_h
 #define XSLImportRule_h
 
-#include "core/loader/cache/CachedStyleSheetClient.h"
 #include "core/loader/cache/ResourcePtr.h"
+#include "core/loader/cache/StyleSheetResourceClient.h"
 #include "core/xml/XSLStyleSheet.h"
 #include <wtf/PassOwnPtr.h>
 
 namespace WebCore {
 
-class CachedXSLStyleSheet;
+class XSLStyleSheetResource;
 
-class XSLImportRule : private CachedStyleSheetClient {
+class XSLImportRule : private StyleSheetResourceClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassOwnPtr<XSLImportRule> create(XSLStyleSheet* parentSheet, const String& href)
@@ -59,7 +59,7 @@
     XSLStyleSheet* m_parentStyleSheet;
     String m_strHref;
     RefPtr<XSLStyleSheet> m_styleSheet;
-    ResourcePtr<CachedXSLStyleSheet> m_cachedSheet;
+    ResourcePtr<XSLStyleSheetResource> m_resource;
     bool m_loading;
 };
 
diff --git a/Source/core/xml/XSLTProcessor.idl b/Source/core/xml/XSLTProcessor.idl
index 5cef21e..f552ed1 100644
--- a/Source/core/xml/XSLTProcessor.idl
+++ b/Source/core/xml/XSLTProcessor.idl
@@ -36,8 +36,8 @@
 ] interface XSLTProcessor {
 
     void importStylesheet([Default=Undefined] optional Node stylesheet);
-    DocumentFragment transformToFragment([Default=Undefined] optional Node source, [Default=Undefined] optional Document docVal);
-    Document transformToDocument([Default=Undefined] optional Node source);
+    [CustomElementCallbacks=Enable] DocumentFragment transformToFragment([Default=Undefined] optional Node source, [Default=Undefined] optional Document docVal);
+    [CustomElementCallbacks=Enable] Document transformToDocument([Default=Undefined] optional Node source);
 
     [Custom] void setParameter(DOMString namespaceURI, DOMString localName, DOMString value);
     [Custom, TreatReturnedNullStringAs=Undefined] DOMString getParameter(DOMString namespaceURI, DOMString localName);
diff --git a/Source/core/xml/parser/CharacterReferenceParserInlines.h b/Source/core/xml/parser/CharacterReferenceParserInlines.h
deleted file mode 100644
index 4e5ed45..0000000
--- a/Source/core/xml/parser/CharacterReferenceParserInlines.h
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- * Copyright (C) 2010 Google, Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CharacterReferenceParserInlines_h
-#define CharacterReferenceParserInlines_h
-
-#include <wtf/text/StringBuilder.h>
-
-namespace WebCore {
-
-static const UChar32 kInvalidUnicode = -1;
-
-inline bool isHexDigit(UChar cc)
-{
-    return (cc >= '0' && cc <= '9') || (cc >= 'a' && cc <= 'f') || (cc >= 'A' && cc <= 'F');
-}
-
-inline UChar asHexDigit(UChar cc)
-{
-    if (cc >= '0' && cc <= '9')
-      return cc - '0';
-    if (cc >= 'a' && cc <= 'z')
-      return 10 + cc - 'a';
-    if (cc >= 'A' && cc <= 'Z')
-      return 10 + cc - 'A';
-    ASSERT_NOT_REACHED();
-    return 0;
-}
-
-inline void unconsumeCharacters(SegmentedString& source, StringBuilder& consumedCharacters)
-{
-    if (consumedCharacters.length() == 1)
-        source.push(consumedCharacters[0]);
-    else if (consumedCharacters.length() == 2) {
-        source.push(consumedCharacters[0]);
-        source.push(consumedCharacters[1]);
-    } else
-        source.prepend(SegmentedString(consumedCharacters.toString()));
-}
-
-template <typename ParserFunctions>
-bool consumeCharacterReference(SegmentedString& source, StringBuilder& decodedCharacter, bool& notEnoughCharacters, UChar additionalAllowedCharacter)
-{
-    ASSERT(!additionalAllowedCharacter || additionalAllowedCharacter == '"' || additionalAllowedCharacter == '\'' || additionalAllowedCharacter == '>');
-    ASSERT(!notEnoughCharacters);
-    ASSERT(decodedCharacter.isEmpty());
-
-    enum EntityState {
-        Initial,
-        Number,
-        MaybeHexLowerCaseX,
-        MaybeHexUpperCaseX,
-        Hex,
-        Decimal,
-        Named
-    };
-    EntityState entityState = Initial;
-    UChar32 result = 0;
-    StringBuilder consumedCharacters;
-
-    while (!source.isEmpty()) {
-        UChar cc = source.currentChar();
-        switch (entityState) {
-        case Initial: {
-            if (cc == '\x09' || cc == '\x0A' || cc == '\x0C' || cc == ' ' || cc == '<' || cc == '&')
-                return false;
-            if (additionalAllowedCharacter && cc == additionalAllowedCharacter)
-                return false;
-            if (cc == '#') {
-                entityState = Number;
-                break;
-            }
-            if ((cc >= 'a' && cc <= 'z') || (cc >= 'A' && cc <= 'Z')) {
-                entityState = Named;
-                continue;
-            }
-            return false;
-        }
-        case Number: {
-            if (cc == 'x') {
-                entityState = MaybeHexLowerCaseX;
-                break;
-            }
-            if (cc == 'X') {
-                entityState = MaybeHexUpperCaseX;
-                break;
-            }
-            if (cc >= '0' && cc <= '9') {
-                entityState = Decimal;
-                continue;
-            }
-            source.push('#');
-            return false;
-        }
-        case MaybeHexLowerCaseX: {
-            if (isHexDigit(cc)) {
-                entityState = Hex;
-                continue;
-            }
-            source.push('#');
-            source.push('x');
-            return false;
-        }
-        case MaybeHexUpperCaseX: {
-            if (isHexDigit(cc)) {
-                entityState = Hex;
-                continue;
-            }
-            source.push('#');
-            source.push('X');
-            return false;
-        }
-        case Hex: {
-            if (isHexDigit(cc)) {
-                if (result != kInvalidUnicode)
-                    result = result * 16 + asHexDigit(cc);
-            } else if (cc == ';') {
-                source.advanceAndASSERT(cc);
-                decodedCharacter.append(ParserFunctions::legalEntityFor(result));
-                return true;
-            } else if (ParserFunctions::acceptMalformed()) {
-                decodedCharacter.append(ParserFunctions::legalEntityFor(result));
-                return true;
-            } else {
-                unconsumeCharacters(source, consumedCharacters);
-                return false;
-            }
-            break;
-        }
-        case Decimal: {
-            if (cc >= '0' && cc <= '9') {
-                if (result != kInvalidUnicode)
-                    result = result * 10 + cc - '0';
-            } else if (cc == ';') {
-                source.advanceAndASSERT(cc);
-                decodedCharacter.append(ParserFunctions::legalEntityFor(result));
-                return true;
-            } else if (ParserFunctions::acceptMalformed()) {
-                decodedCharacter.append(ParserFunctions::legalEntityFor(result));
-                return true;
-            } else {
-                unconsumeCharacters(source, consumedCharacters);
-                return false;
-            }
-            break;
-        }
-        case Named: {
-            return ParserFunctions::consumeNamedEntity(source, decodedCharacter, notEnoughCharacters, additionalAllowedCharacter, cc);
-        }
-        }
-
-        if (result > UCHAR_MAX_VALUE)
-            result = kInvalidUnicode;
-
-        consumedCharacters.append(cc);
-        source.advanceAndASSERT(cc);
-    }
-    ASSERT(source.isEmpty());
-    notEnoughCharacters = true;
-    unconsumeCharacters(source, consumedCharacters);
-    return false;
-}
-
-}
-
-#endif // CharacterReferenceParserInlines_h
diff --git a/Source/core/xml/parser/XMLDocumentParser.cpp b/Source/core/xml/parser/XMLDocumentParser.cpp
index 5f568c7..197868f 100644
--- a/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -55,8 +55,8 @@
 #include "core/loader/FrameLoader.h"
 #include "core/loader/ImageLoader.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/CachedScript.h"
 #include "core/loader/cache/ResourceFetcher.h"
+#include "core/loader/cache/ScriptResource.h"
 #include "core/page/Frame.h"
 #include "core/page/UseCounter.h"
 #include "core/platform/network/ResourceError.h"
@@ -1052,7 +1052,7 @@
         if (scriptLoader->readyToBeParserExecuted()) {
             scriptLoader->executeScript(ScriptSourceCode(scriptLoader->scriptContent(), document()->url(), m_scriptStartPosition));
         } else if (scriptLoader->willBeParserExecuted()) {
-            m_pendingScript = scriptLoader->cachedScript();
+            m_pendingScript = scriptLoader->resource();
             m_scriptElement = element;
             m_pendingScript->addClient(this);
 
diff --git a/Source/core/xml/parser/XMLDocumentParser.h b/Source/core/xml/parser/XMLDocumentParser.h
index d680c4a..7233482 100644
--- a/Source/core/xml/parser/XMLDocumentParser.h
+++ b/Source/core/xml/parser/XMLDocumentParser.h
@@ -40,7 +40,7 @@
 namespace WebCore {
 
 class ContainerNode;
-class CachedScript;
+class ScriptResource;
 class ResourceFetcher;
 class DocumentFragment;
 class Document;
@@ -179,7 +179,7 @@
 
         XMLErrors m_xmlErrors;
 
-        ResourcePtr<CachedScript> m_pendingScript;
+        ResourcePtr<ScriptResource> m_pendingScript;
         RefPtr<Element> m_scriptElement;
         TextPosition m_scriptStartPosition;